什麼是JWT,什麼是JWT Bearer就不累述了。在ASP.NET WEBAPI中使用JWT Bearer的時候比較多,最近我終於學會配置了。
第一步:對應項目安裝Microsoft.AspNetCore.Authentication.JwtBearer
第二步:appsettings.json中,添加JWT的配置,參考代碼如下,注意SecretKey不能設置成太短的純數字,不然要報錯
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"JWT": {
"SecretKey": "[email protected]",
"Issuer": "2222",
"Expires": 10,
"Audience": "22333"
}
}
第三步:在Program.cs中,將JWT添加到服務中,參考代碼
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuer = builder.Configuration["JWT:Issuer"],
ValidateAudience = true,
ValidAudience = builder.Configuration["JWT:Audience"],
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:SecretKey"]))
};
});
第四步:在Program.cs中,啓用認證,添加代碼如下,這個必須添加在app.UseAuthorization();
前面,兩個名稱很像,注意區別。
app.UseAuthentication();
第五:創建一個方法,專門用來生成JWT的Token,參考代碼
public string CreateToken()
{
// 1. 定義需要使用到的Claims
var claims = new[]
{
new Claim("Id", "9527"),
new Claim("Name", "Admin")
};
// 2. 從 appsettings.json 中讀取SecretKey
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:SecretKey"]));
// 3. 選擇加密算法
var algorithm = SecurityAlgorithms.HmacSha256;
// 4. 生成Credentials
var signingCredentials = new SigningCredentials(secretKey, algorithm);
// 5. 從 appsettings.json 中讀取Expires
var expires = Convert.ToDouble(configuration["JWT:Expires"]);
// 6. 根據以上,生成token
var token = new JwtSecurityToken(
configuration["JWT:Issuer"], //Issuer
configuration["JWT:Audience"], //Audience
claims, //Claims,
DateTime.Now, //notBefore
DateTime.Now.AddDays(expires), //expires
signingCredentials //Credentials
);
// 7. 將token變爲string
var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
return jwtToken;
}
注意:claims裏面的內容應該要從外面創建來,動態存一些用戶信息之類的;configuration["JWT:SecretKey"]
這種是在讀取配置文件appsettings.json
中的配置,configuration
要在類的構造函數中注入進來。
第六,找到有關登錄方法的控制器,在登錄成功之後,將token返回給用戶,參考代碼
public IActionResult Login(LoginDto loginDto)
{
if (!ModelState.IsValid)
{
return BadRequest("Email or Password can not be empty");
}
var token = _makeToken.CreateToken();
return Ok(token);
}
第七,在對應業務的控制器上,或者控制器下面的方法上,加上特性[Authorize]
就這樣,.NET 6實現了基本的 JWT Bearer認證和授權配置。