一。首先webapi域内创建一个token的ViewModel,比如:TokenManagement
public class TokenManagement
{
[JsonProperty("secret")]
public string Secret { get; set; }
[JsonProperty("issuer")]
public string Issuer { get; set; }
[JsonProperty("audience")]
public string Audience { get; set; }
[JsonProperty("accessExpiration")]
public int AccessExpiration { get; set; }
[JsonProperty("refreshExpiration")]
public int RefreshExpiration { get; set; }
}
二。在appsettings.json配置文件里添加相关配置信息
"tokenManagement": {
"secret": "SecureKeySecureKeySecureKeySecureKeySecureKeySecureKey",
"issuer": "webapi.cn",
"audience": "WebApi",
"accessExpiration": 30,
"refreshExpiration": 60
}
三。在StartUp类的ConfigureServices方法里注册JWT服务
//添加JWT服务
services.Configure<TokenManagement>(Configuration.GetSection("tokenManagement"));
var token = Configuration.GetSection("tokenManagement").Get<TokenManagement>();
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,//是否验证私匙
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),//拿到私匙
ValidIssuer = token.Issuer,
ValidAudience = token.Audience,
ValidateIssuer = true,//是否验证issurer签发者issuer代表颁发Token的Web应用程序,
ValidateLifetime = true,//是否验证失效时间
ClockSkew = TimeSpan.Zero, // // 默认允许 300s 的时间偏移量,设置为0
ValidateAudience = true//是否验证Audience audience是Token的受理者
};
});
四。再在StartUp类Configure方法里启用JWT身份组件
//启用JWT身份验证组件
app.UseAuthentication();//认证中间件
五。相应的控制器上标注[Authorize]特性即可,跳过的控制器或action上标注[AllowAnonymous]即可