如何在 JwtBearer 和 System.IdentityModel.Tokens.Jwt 的 asp.net 核心中自定义 bearer header 关键字?

How to customize bearer header keyword in asp.net core for JwtBearer and System.IdentityModel.Tokens.Jwt?

使用 using Microsoft.AspNetCore.Authentication.JwtBearer; 我一直无法弄清楚如何将 header 中的 "Bearer " 键更改为其他内容,在这种情况下我希望它是 "Token ".

Startup.cs

services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
             {
                 x.RequireHttpsMetadata = false;
                 x.SaveToken = true;
                 x.TokenValidationParameters = new TokenValidationParameters
                 {
                     ValidateIssuerSigningKey = true,
                     IssuerSigningKey = new SymmetricSecurityKey(key),
                     ValidateIssuer = false,
                     ValidateAudience = false,
                     ValidateLifetime = true,
                     ValidIssuer = Configuration.GetValue<string>("JwtIssuer"),
                     ValidAudience = Configuration.GetValue<string>("JwtAudience"),
                 };
                 x.Events = new JwtBearerEvents
                 {
                     OnAuthenticationFailed = context =>
                     {
                         if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                         {
                             context.Response.Headers.Add("Token-Expired", "true");
                         }
                         return Task.CompletedTask;
                     }
                 };
             });

当我做类似

的事情时
GET {{protocol}}://{{url}}/users HTTP/1.1
Authorization: Bearer {{token}}

令牌有效,但我不知道如何将其自定义为类似的东西。

GET {{protocol}}://{{url}}/users HTTP/1.1
Authorization: Token {{token}}


前缀 Bearer ... 来自您设置为默认身份验证方案的 JwtBearerDefaults.AuthenticationScheme

如果您愿意,可以像这样使用 custom authentication 或类似的方法:

// Add authentication
services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CustomAuthOptions.DefaultScheme;
    options.DefaultChallengeScheme = CustomAuthOptions.DefaultScheme;
})
// Call custom authentication extension method
.AddCustomAuth(options =>
    {
    // Configure password for authentication
    options.AuthKey = "custom auth key";
});

.. 或者甚至可以结合 custom scheme name with .AddJwtBearer(x => ...) - never tried this. Or maybe you are just looking for something like protecting your API with API Keys.

JwtBearer 身份验证处理程序的实现存在于 JwtBearerHandler 内部,其中 Authorization header 使用 Bearer ... 格式读取和拆分。这是它的样子:

string authorization = Request.Headers["Authorization"];

// If no authorization header found, nothing to process further
if (string.IsNullOrEmpty(authorization))
{
    return AuthenticateResult.NoResult();
}

if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
    token = authorization.Substring("Bearer ".Length).Trim();
}

// If no token found, no further work possible
if (string.IsNullOrEmpty(token))
{
    return AuthenticateResult.NoResult();
}

如上面的代码所示,这被硬编码为使用 Bearer。但是,JwtBearerEvents 包含一个 OnMessageReceived 属性,它允许您挂接到从传入请求中检索 JWT 的过程。如果您为此事件提供实现,则可以根据需要使用自己的处理来提取 JWT。

对上面的实现进行一些更改,该事件处理程序实现将像这样:

x.Events = new JwtBearerEvents
{
    // ...
    OnMessageReceived = context =>
    {
        string authorization = context.Request.Headers["Authorization"];

        // If no authorization header found, nothing to process further
        if (string.IsNullOrEmpty(authorization))
        {
            context.NoResult();
            return Task.CompletedTask;
        }

        if (authorization.StartsWith("Token ", StringComparison.OrdinalIgnoreCase))
        {
            context.Token = authorization.Substring("Token ".Length).Trim();
        }

        // If no token found, no further work possible
        if (string.IsNullOrEmpty(context.Token))
        {
            context.NoResult();
            return Task.CompletedTask;
        }

        return Task.CompletedTask;
    }
};