使用平台
- .net core 3.1
- vs 2019
- post man
源码地址
https://github.com/tx1721110240/Json-Web-Token-JWT
文章目录
前言
本章讲述,jwt的基本用法及信息的传递
一、首先创建我们需要两个项目
AuthenticationCenter 为鉴权中心,Demo是我们要访问的API
我们需要将未登录的用户账号密码发送至鉴权中心,然后鉴权中心验证登录通过后,返回Token。然后我们将Token发送给用户,用户每次访问都需要携带token进行访问
二、编码
1.AuthenticationCenter
鉴权中心主要负责,验证登录并返回Token,代码如下(示例仅包含主要部分):
public string GetToken(string UserName)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, UserName),
new Claim("NickName","李四"),
new Claim("Role","Administrator"),//传递其他信息
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
/**
* Claims (Payload)
Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段,下面节选一些字段:
iss: The issuer of the token,token 是给谁的
sub: The subject of the token,token 主题
exp: Expiration Time。 token 过期时间,Unix 时间戳格式
iat: Issued At。 token 创建时间, Unix 时间戳格式
jti: JWT ID。针对当前 token 的唯一标识
除了规定的字段外,可以包含其他任何 JSON 兼容的字段。
* */
var token = new JwtSecurityToken(
issuer: _configuration["issuer"],
audience: _configuration["audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(5),//5分钟有效期
signingCredentials: creds);
string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
return returnToken;
}
2.Demo
Demo主要负责验证访问Token是否合法,代码如下(示例仅包含主要部):
public void ConfigureServices(IServiceCollection services)
{
#region jwt校验
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = true,//是否验证失效时间
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidAudience = this.Configuration["audience"],//Audience
ValidIssuer = this.Configuration["issuer"],//Issuer,这两项和前面签发jwt的设置一致
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.Configuration["SecurityKey"])),//拿到SecurityKey
//AudienceValidator = (m, n, z) =>
//{
// return m != null && m.FirstOrDefault().Equals(this.Configuration["audience"]);
//},//自定义校验规则,可以新登录后将之前的无效
};
});
#endregion
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
#region jwt
app.UseAuthentication();//注意添加这一句,启用验证
#endregion
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
记得在类上加特性[Microsoft.AspNetCore.Authorization.Authorize]
如果有不行进行校验的方法可以使用特性[Microsoft.AspNetCore.Authorization.AllowAnonymous]
三、测试使用
1.首先测试无需授权的方法
2.访问鉴权中心获得token
3.不使用token访问api接口
401代表没有权限访问
4.使用token访问api接口
携带token可以正常访问接口
总结
JWT原理请查看前一篇文章:点击跳转
JWT是很简单轻便的使用方式,但需要自己添加很多功能才会变得更加安全,因此若是.net core 的项目推荐使用IdentityServer4