如何使 .NET Core 6 不需要 jwt 持有者令牌?

How to make jwt bearer token not required in .NET Core 6?

我有 JWT Bearer 身份验证的配置,但有时我不想使用 JWT 令牌,而是想在请求中使用 API KEY header 并在中间件中检查此密钥。

但在那种情况下,当我不将不记名令牌放入 header 时,我总是使用未经授权的响应代码进行响应。

如何禁用不记名令牌检查?

我的配置:

    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(options =>
    {
        // options.RequireHttpsMetadata = false;
        // options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            ValidateIssuer = true,
            ValidateAudience = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)),
            ValidIssuer = jwtSettings.Issuer,
            ValidAudiences = jwtSettings.Audiences,
            ClockSkew = TimeSpan.Zero // remove delay of token when expire
        };
     });

您可以在方法中使用 [AllowAnonymous] 属性来禁用身份验证检查。

然后,创建一个 ActionFilterAttribute 并将其应用于相同的方法:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace YourNameSpace
{
    public class RequireYourKeyHeader : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if(!filterContext.HttpContext.Request.Headers.TryGetValue("YourKey", out string headerValue))
            {
                filterContext.Result = new BadRequestObjectResult("missing headr value");
            }
            
            // TODO: check if value passed in the header is actually valid
        }
    }
}

申请[RequireYourKeyHeader]

您可以使用 multipe AuthenticationSchemes,而不是以更惯用的方式检查中间件。有关详细信息,请参阅 MSDN link,但在非常高的级别上,您可以分配添加多个身份验证方案,每个方案都有不同的方案。然后在使用 autorize 属性时引用此方案名称(例如 [Authorize(AuthenticationSchemes = "Api-Key-Scheme")])。

services
  .AddAuthentication()
  .AddJwtBearer(options => { .. })
  .AddApiKey(options => { .. });  // custom code

上面的 .AddApiKey() 方法需要自定义 AuthenticationHandler<T> 实现,可以在此处找到如何执行此操作的示例 - https://josef.codes/asp-net-core-protect-your-api-with-api-keys/