JWT for net 6
01------------------appsettings.json----------------
"JWT": {
"SecretKey": "assdfghkldsf@123!",
"Issuer": "2222",
"Expires": 10,
"Audience": "22333"
}
02-----------------program---------------------------
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"]))
};
});
var app = builder.Build();
//鉴权授权
app.UseAuthentication();
app.UseAuthorization();
03------login---------------------------------
[HttpGet]
public string login()
{
// 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;
}