why is 404 happened when i request action in a web API project using ASP.NET Core 5.0 authentication service?

yi lin 40 Reputation points
2023-06-27T07:23:09.83+00:00

when i set [Authorize] to controller , the request "/login/login",the response is "404 not found". when i delete [Authorize], it's work . why was it happened? Here is the code snippet:


public class Startup
{

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddIdentity<IdentityUser, IdentityRole>(options =>
            {
                options.SignIn.RequireConfirmedAccount = true;
            })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddAuthorization();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

    //[Authorize( AuthenticationSchemes = "Identity.Application")]  try and not work
    [Authorize] try and not work
    [ApiController]
    [Route("[controller]/[action]/{id?}")]
    public class LoginController : ControllerBase
    {
        
        [HttpGet]
        public async Task<object> LoginAsync()
        {
            some codes
        }

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | ASP.NET API
Developer technologies | ASP.NET | Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2023-06-27T09:56:35.7166667+00:00

    A login controller cannot have an [Authorize] attribute. Users that are trying to login cannot access the controller because they have not logged in.

    Are you sure a 404 is returned and not a 401? Maybe the 404 is due to submitting a post but a post action does not exist?

    1 person found this answer helpful.

  2. Anonymous
    2023-06-27T10:03:03.7833333+00:00

    Hi,@yi lin,

    Here's part of source codes of Identity,You could see that Identity is based on Cookie Authentication,and it set

    o.LoginPath = new PathString("/Account/Login"); As mentioned in the doucment,

    The LoginPath property is used by the handler for the redirection target when handling ChallengeAsync. The current url which is added to the LoginPath as a query string parameter named by the ReturnUrlParameter. Once a request to the LoginPath grants a new SignIn identity, the ReturnUrlParameter value is used to redirect the browser back to the original url.

    public static IdentityBuilder AddIdentity<TUser, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TRole>(
            this IServiceCollection services,
            Action<IdentityOptions> setupAction)
            where TUser : class
            where TRole : class
        {
            // Services used by identity
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
                options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
                options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
            })
            .AddCookie(IdentityConstants.ApplicationScheme, o =>
            {
                o.LoginPath = new PathString("/Account/Login");
                o.Events = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
                };
            })
            .AddCookie(IdentityConstants.ExternalScheme, o =>
            {
                o.Cookie.Name = IdentityConstants.ExternalScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            })
            .AddCookie(IdentityConstants.TwoFactorRememberMeScheme, o =>
            {
                o.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme;
                o.Events = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = SecurityStampValidator.ValidateAsync<ITwoFactorSecurityStampValidator>
                };
            })
            .AddCookie(IdentityConstants.TwoFactorUserIdScheme, o =>
            {
                o.Cookie.Name = IdentityConstants.TwoFactorUserIdScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            });
    
    
    

    In short,you should set Authorize Attribute on the endpoins you want to protect instead of login endpoint(You would fail the authentication and redirect to loginpath which does not exist in your app and get 404 error as the result )

    And here's the basic concept of Authentication in Asp.net core,hopes help.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Ruikai Feng

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.