简体   繁体   中英

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,
            };
        });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM