gpt4 book ai didi

c# - 如何在 asp.net core 中为 JwtBearer 和 System.IdentityModel.Tokens.Jwt 自定义 bearer header 关键字?

转载 作者:行者123 更新时间:2023-11-30 14:44:53 29 4
gpt4 key购买 nike

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

启动.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}}

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

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


最佳答案

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

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

关于c# - 如何在 asp.net core 中为 JwtBearer 和 System.IdentityModel.Tokens.Jwt 自定义 bearer header 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56857905/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com