什么是JWT
Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。JWT的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该token也可直接被用于认证,也可被加密。详细阅读请浏览
什么是 JWT -- JSON WEB TOKEN - 简书 (jianshu.com)
上文我们在创建后台项目的时候已经通过NuGet安装包的方式将JWT引入到了项目。
在后台项目中支持JWT
(1)配置JWT参数
core中没有传统的asp.net中的web.config文件来进行系统参数配置,但是提供了一个轻量级的appsettings.json文件来管理组件中的参数。
我们打开appsettings.json文件,加入JWT配置参数
"tokenManagement": {
"secret": "123456123456123456",
"issuer": "webapi.cn",
"audience": "WebApi",
"accessExpiration": 30,
"refreshExpiration": 60
}
中间配置了秘钥,访问到期时间,刷新时间,接收方
(2)根据配置将JWT组件安装到工程中
打开Startup.cs文件,定位到ConfigureServices方法
public void ConfigureServices(IServiceCollection services)
{
//读取jwt配置
services.Configure<TokenManagement>(Configuration.GetSection("tokenManagement"));
var token = Configuration.GetSection("tokenManagement").Get<TokenManagement>();
//添加JWT认证到系统服务中
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.UTF8.GetBytes(token.Secret)),
ValidIssuer = token.Issuer,
ValidAudience = token.Audience,
ValidateIssuer = false,
ValidateAudience = false
};
});
}
到这里我们后台就已经支持了JWT组件,但是还没有开始使用。