如何在 asp.net core 中为 JwtBearer 和 System.IdentityModel.Tokens.Jwt 自定义承载头关键字?

las*_*ink 6 c# bearer-token .net-core asp.net-core

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

启动文件

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;
                     }
                 };
             });
Run Code Online (Sandbox Code Playgroud)

当我做类似的事情时

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

Run Code Online (Sandbox Code Playgroud)

该令牌有效,但我无法弄清楚如何将其自定义为类似的东西。

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


Run Code Online (Sandbox Code Playgroud)

Kir*_*kin 15

JwtBearer 身份验证处理程序的实现位于 内部JwtBearerHandler,其中Authorization使用格式读取和拆分标头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();
}
Run Code Online (Sandbox Code Playgroud)

如上面的代码所示,这是硬编码以使用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;
    }
};
Run Code Online (Sandbox Code Playgroud)