![](/img/trans.png)
[英]Encoding JWT Token Using System.IdentityModel.Tokens.Jwt in ASP.NET 5
[英]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”。
啟動.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}}
在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(); }
如上面的代碼所示,這是硬編碼以使用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;
}
};
Prefix Bearer ...
來自您設置為默認身份驗證方案的JwtBearerDefaults.AuthenticationScheme
。
如果您願意,可以使用像這樣或類似的自定義身份驗證:
// 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";
});
.. 或者甚至可以將自定義方案名稱與.AddJwtBearer(x => ...)
- 從未嘗試過。 或者,您可能只是在尋找諸如使用 API Keys 保護您的 API 之類的東西。
這個實現對我來說非常簡單: link
services.AddAuthentication().AddJwtBearer(options => {
options.Events = new JwtBearerEvents {
OnMessageReceived = ctx => {
if (ctx.Request.Headers.ContainsKey("SpecialApiKey"))
{
var bearerToken = ctx.Request.Headers["SpecialApiKey"].ElementAt(0);
var token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;
ctx.Token = token;
}
return Task.CompletedTask;
}
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.