ASP.NET JWT 授权returns NotFound

ASP.NET JWT authorization returns NotFound

我正在做一个 api 项目,需要使用 jwt,我已经在启动时配置了它,但每当我在操作中使用 [Authorize] 时,我都会收到 404 Notfound 响应。我还注意到,如果我使用 [Authorize(AuthenticationSchemes = "Bearer")],它将正常工作。我不想使用那篇冗长的声明。请问可能是什么原因?下面是我在启动时的 jwt 配置。

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

试试这个:-

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

或者您可以像这样在整个应用程序中授权策略:-

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

因此,不需要在方法上添加 [Authorize(AuthenticationSchemes = "Bearer")]