前言
随着现在信息化越来越快,Net Core在平时项目中使用的频率越来越高,而且微软对应的教程也增加了对应的中文版,可以说技术门槛越来越低了,今天主要的就是记录一下如何使用JWT验证方式的一篇小文章。
配置
首先 必不可少的就是Nuget包的引用下载,JWT验证只涉及到一个包
Microsoft.AspNetCore.Authentication.JwtBearer 搜索安装即可
代码展示
Startup.cs 配置
//注意:Configuration.GetSection 这个方法是我自己封装好的用于读取 appsetting.json配置的信息
/* 示例 JwtConfig就是对应节点的实体话
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Jwt": {
"Issuer": "Issuer",
"Audience": "Audience",
"SigningKey": "EF1DA5B4-C7FA-4240-B997-7D1701BF9BE2"
}
}
*/
//ConfigureServices 中需要进行添加的信息
#region Token验证信息 JWT
读取JWT的配置信息
var jwtconfig = Configuration.GetSection("Jwt").Get<JwtConfig>();
JWT身份认证
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(option =>
{
option.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = jwtconfig.Issuer,
ValidAudience = jwtconfig.Audience,
ValidateIssuer = true,
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtconfig.SigningKey)),
// 缓冲过期时间,总的有效时间等于这个时间加上jwt的过期时间,如果不配置,默认是5分钟
ClockSkew = TimeSpan.FromSeconds(5)
};
option.Events = new JwtBearerEvents
{
//此处为权限验证失败后触发的事件
OnChallenge = context =>
{
//此处代码为终止.Net Core默认的返回类型和数据结果,这个很重要哦,必须
context.HandleResponse();
//自定义自己想要返回的数据结果,我这里要返回的是Json对象,通过引用Newtonsoft.Json库进行转换
var payload = JsonConvert.SerializeObject(new { message = "授权未通过,Token无效", status = false, code = 401 });
//自定义返回的数据类型
context.Response.ContentType = "application/json";
//自定义返回状态码,默认为401 我这里改成 200
context.Response.StatusCode = StatusCodes.Status200OK;
//输出Json数据结果
context.Response.WriteAsync(payload);
return Task.FromResult(0);
}
};
});
services.AddOptions().Configure<JwtConfig>(Configuration.GetSection("Jwt"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
#endregion
//Configure 中间需要补充 一下验证方式
// JWT身份认证
app.UseAuthentication();
//添加用户校验
app.UseAuthorization();
以上配置好了 就基本上可以使用JWT验证了 接下来我告诉大家该如何进行使用
使用的话 我自己也封装了一个帮助类 直接进行调用
/// <summary>
/// JWT帮助类信息
/// </summary>
public class JwtHelper
{
/// <summary>
/// 颁发JWT字符串
/// </summary>
/// <param name="tokenModel"></param>
/// <returns></returns>
public static string IssueJwt(Claim[] claim)
{
// 读取对应的配置信息
string iss = ConfigHelper.GetSectionValue("Jwt:Issuer");
string aud = ConfigHelper.GetSectionValue("Jwt:Audience");
string secret = ConfigHelper.GetSectionValue("Jwt:SigningKey");
//加密关键字
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
//编码格式
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//token存储相关信息
var token = new JwtSecurityToken(
issuer: iss,
audience: aud,
claims: claim,
notBefore: DateTime.Now,
expires: DateTime.Now.AddSeconds(300),
signingCredentials: creds);
var jwtHandler = new JwtSecurityTokenHandler();
//生成对应的编码信息
var encodedJwt = jwtHandler.WriteToken(token);
return encodedJwt;
}
/// <summary>
/// 解析
/// </summary>
/// <param name="jwtStr"></param>
/// <returns></returns>
public static List<Claim> SerializeJwt(string jwtStr)
{
var jwtHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
object role;
try
{
jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
var list = jwtToken.Claims.ToList();
return list;
}
}
控制器层使用示例:
/// <summary>
/// 测试获取token信息
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult<string> Get()
{
//参数存储的信息
var claim = new Claim[]{
new Claim("UserName", "测试"),
new Claim("UserId", "10086")
};
//生成证书
var token = JwtHelper.IssueJwt(claim);
//解析证书
var data= JwtHelper.SerializeJwt(token);
return Ok(new { token = token, data= data });
}
/// <summary>
/// 在需要身份认证的方法添加[Authorize]
/// </summary>
[Authorize]
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
然后 整体就基本上结束了 这样一个基本的JWT验证就已经进行配置好了呢
题外话,要是系统的用的不习惯的话 可以自定义特性进行处理 类似Framework
不过需要添加对应的拦截器进行信息处理 临时存储方便后续的使用处理