NuGet引用

System.IdentityModel.Tokens.Jwt

appsettings.json里添加

"JwtSettings": {
"Issuer": "thisisissuer",
"Audience": "thisisaudience",
"SecretKey": "abcdefglsdkfjlsdkfd1"
}

添加扩展

 
public static IServiceCollection AddJwtBearerProvider(this IServiceCollection services, IConfiguration Configuration)
{
services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
JwtSettings setting = new JwtSettings();
Configuration.Bind("JwtSettings", setting);
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(config =>
{
//jwt默认是Authorization:'Bearer' Token 形式 自定义成 Bearer
config.Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
var token = context.Request.Headers["auth"];
context.Token = token.FirstOrDefault();
return Task.CompletedTask;
}
};
config.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
//NameClaimType = JwtClaimTypes.Name,
//RoleClaimType = JwtClaimTypes.Role,
//Token颁发机构
ValidIssuer = setting.Issuer,
//颁发给谁
ValidAudience = setting.Audience,
//这里的key要进行加密,需要引用Microsoft.IdentityModel.Tokens
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(setting.SecretKey)),
ValidateIssuerSigningKey = true,
ValidateIssuer = true, //Whether or not validate Issuer
ValidateAudience = true, //Whether or not validate Audience
////是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
ValidateLifetime = true,
////允许的服务器时间偏移量
ClockSkew = TimeSpan.FromSeconds(1)
};
});
return services;
}

启用验证 此处会启用jwt验证

app.UseAuthentication();

登陆接口生成token

var claims = new Claim[] {
new Claim(ClaimTypes.Name,authInfo.un),
//new Claim(ClaimTypes.Role, "ma"),//多个权限重复添加
//new Claim(ClaimTypes.Role, "mamama"),
//new Claim("EmployeeNumber", "true"),//添加用户访问权限
new Claim("emp",JsonConvert.SerializeObject(authInfo)),
new Claim(JwtRegisteredClaimNames.Sub, "Client"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
//这个就是过期时间,目前是8小时,可自定义,注意JWT有自己的缓冲过期时间
new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddHours(1)).ToUnixTimeSeconds()}"),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(setting.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
setting.Issuer,
setting.Audience,
claims,
signingCredentials: creds);
string token=new JwtSecurityTokenHandler().WriteToken(token);