Search code examples
asp.netasp.net-corejwtasp.net-apicontroller

ASP.NET JWT authorization returns NotFound


I'm working on an api project and need to use jwt, I've configured it on the startup but I get a 404 Notfound response anytime I use [Authorize] on the action. I also noticed that if I use [Authorize(AuthenticationSchemes = "Bearer")], It will work fine. And I dont want to be using that long statement. Please what could be the cause? Below is my jwt configuration on the startup.

services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration.GetSection("JWTConfigurations:SecretKey").Value)),
                ValidateIssuer = true,
                ValidIssuer = Configuration.GetSection("JWTConfigurations:Issuer").Value,
                ValidateAudience = true,
                ValidAudience = Configuration.GetSection("JWTConfigurations:Audience").Value,
            };
        });

Solution

  • Try this:-

    services.AddAuthentication(options => {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;  //add this to your code
    })
     .AddJwtBearer(...);
    
    

    Or you can auth policy throughout the whole application like this:-

      services.AddControllers(opt => {
                var policy = new AuthorizationPolicyBuilder("Bearer").RequireAuthenticatedUser().Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            })
    

    So for that, won't need to put [Authorize(AuthenticationSchemes = "Bearer")] on methods.