[英]Setting up JWT authentication in .NET core 2.0
我正在將現有的.NET Core 1.1.4代碼遷移到.NET Core 2.0。 看來我們必須對其進行更改,以便將身份驗證作為服務添加到ConfigureService()
而不是在Configure()
函數中。
我們目前正在使用以下屬性:
AutomaticAuthenticate
AutomaticChallenge
TokenValidationParameters.IssuerSigningKey
TokenValidationParameters.ValidAudence
TokenValidationParameters.ValidateIssuerSigningKey
TokenValidationParameters.ValidateLifetime
TokenValidationParameters.ValidIssuer
在遷移文檔中, AddJwtBearer()
在受眾群體中有一個options參數,這就是我所使用的。 但是,我檢查了options類的接口,似乎沒有其他需要的值。 但是,沒有TokenValidationParameters屬性。 我可以實例化我現在擁有的相同令牌並使用它嗎?
1.1.4版本:
app.UseAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("AppConfiguration:Key").Value)),
ValidAudience = Configuration.GetSection("AppConfiguration:SiteUrl").Value,
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ValidIssuer = Configuration.GetSection("AppConfiguration:SiteUrl").Value
}
});
2.0.0版本:
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
var siteUrl = Configuration.GetSection("AppConfiguration:SiteUrl").Value;
options.Audience = siteUrl;
options.Authority = siteUrl;
options.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("AppConfiguration:Key").Value)),
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ValidIssuer = Configuration.GetSection("AppConfiguration:SiteUrl").Value,
};
});
AutomaticAuthenticate
和AutomaticChallenge
是否變為:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);
沒錯,ASP.NET Core 2.0中的AutomaticAuthenticate
和AutomaticChallenge
屬性都消失了。
它們被AddAuthentication
方法的重載代替,您可以在其中指定默認的身份驗證方案。
從ASP.NET Core 1.x到ASP.NET Core 2.0的遷移文檔涵蓋了這一點。
這樣做意味着在每個請求上,將運行與該方案關聯的身份驗證處理程序(在您的情況下,是JWT承載令牌處理程序)以嘗試對請求進行身份驗證。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.