JWT主要由三部分構成,header、 payload 、signature,下面給出詳細的TOKEN生成及使用代碼。
1、註冊JWT服務
public void ConfigureServices(IServiceCollection services)
{
//註冊JWT
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt => {
opt.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidAudience = Configuration["JWT:Audience"],
ValidIssuer = Configuration["JWT:Issuer"],
//ClockSkew = TimeSpan.FromSeconds(300), //時間偏移量
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["JWT:SecurityKey"]))
};
});
}
2、配置JWT,啟用認證
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//啟用驗證
app.UseAuthorization();
}
3、配置appsettings.json
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"JWT": {
"SecurityKey": "fcf6dc95-6ba4-48ff-b584-a10fd61a054b",
"Issuer": "robinxu",
"Audience": "robinxu"
},
"AllowedHosts": "*"
}
4、服務端生成Token
/// <summary>
/// 生成Token
///
/// <param>
/// <returns>
[AllowAnonymous]
[HttpPost]
[Route("Token")]
public IActionResult Token([FromBody]TokenRequest request)
{
if (request.userName == "robin" && request.password == "666666")
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim("name", request.userName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(
issuer: _configuration["JWT:Issuer"],
audience: _configuration["JWT:Audience"],
claims: claims,
notBefore: DateTime.Now,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
date = DateTime.Now.ToString()
});
}
else
{
return BadRequest("賬號或密碼驗證失敗");
}
}
public class TokenRequest
{
public string userName { get; set; }
public string password { get; set; }
}
5、獲取Token
請求:
{
"userName":"robin",
"password":"666666"
}
響應:
{
"token": "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmZTczM2EyZC00MDYyLTRhOGEtOTNhZC00YThkMjliNDQyN2EiLCJuYW1lIjoicm9iaW4iLCJuYmYiOjE1ODE2ODEyMjQsImV4cCI6MTU4MTY4MzAyNCwiaXNzIjoieHVndW9odWkiLCJhdWQiOiJ4dWd1b2h1aSJ9.ttxs3NnZ3fTTvvcMymhpMPBTgP61oQuqc-klVwCYuoY",
"date": "2020/2/14 19:53:45"
}
6、驗證Token請求地址
// <summary>
/// 測試
///
/// <returns>
[HttpGet]
[Route("Test")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public string Test()
{
return Guid.NewGuid().ToString();
}
7、驗證Token請求圖示
閱讀更多 友調 的文章