.net 使用Microsoft.IdentityModel.Tokens.Jwt进行身份认证

.net 使用Microsoft.IdentityModel.Tokens.Jwt进行身份认证

什么是JWT

JWT (全称:Json Web Token)是一个开放标准(RFC 7519),它定义了一种紧凑的、自包含的方式,用于作为 JSON 对象在各方之间安全地传输信息。该信息可以被验证和信任,因为它是数字签名的。

jwt和token区别

jwt和token区别主要体现在接收的信息是否需要进入数据库查询信息。

服务端验证客户端发来的token信息要进行数据的查询操作;而JWT验证客户端发来的token信息不需要, JWT使用密钥校验不用数据库的查询。

.Net Core使用JWT

1、NUGET添加引用包

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

2、生成jwt字符串

public static string Loginjwt(long ID)
 {
 //引用System.IdentityModel.Tokens.Jwt
 DateTime utcNow = DateTime.UtcNow;

 SecurityKey securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key));

 var claims = new List<Claim>() {
 new Claim("ID",ID.ToString()),
 new Claim("Name","fan")
 };
 JwtSecurityToken jwtToken = new JwtSecurityToken(
 issuer: "fan",
 audience: "audi~~!",
 claims: claims,
 notBefore: utcNow,
 expires: utcNow.AddYears(1),
 signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
 );

 //生成token方式1
 string jwtString = new JwtSecurityTokenHandler().WriteToken(jwtToken);

return jwtString;
 }

3、对jwt进行校验和解析

 public static uint? Checkjwt(string jwtString)
 {
 SecurityKey securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key));

 //校验token
 var validateParameter = new TokenValidationParameters()
 {
 ValidateLifetime = true,
 ValidateAudience = true,
 ValidateIssuer = true,
 ValidateIssuerSigningKey = true,
 ValidIssuer = "fan",
 ValidAudience = "audi~~!",
 IssuerSigningKey = securityKey,
 };

 try
 {
 //校验并解析token
 var claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(jwtString, validateParameter, out SecurityToken validatedToken);//validatedToken:解密后的对象
 var jwtPayload = ((JwtSecurityToken)validatedToken).Payload.SerializeToJson(); //获取payload中的数据

return Convert.ToUInt32(JsonHelper.GetObject<JwtRootobject>(jwtPayload).ID);
 }
 catch (SecurityTokenExpiredException)
 {
 //表示过期
 throw new Exception("登录过期");
 }
 catch (SecurityTokenException)
 {
 //表示token错误
 throw new Exception("token错误");
 }
 catch (Exception)
 {
 throw new Exception("验证失败");
 }

 //不校验,直接解析token
 //jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(token1);
 }

4、针对请求进行头部验证Authorization

public override void OnActionExecuting(ActionExecutingContext context)
 {
if (context.HttpContext.Request != && context.HttpContext.Request.Headers != && context.HttpContext.Request.Headers["Authorization"].Count > 0)
 {
 var token = context.HttpContext.Request.Headers["Authorization"];
if (string.IsOrWhiteSpace(token))
 {
 throw new CustomException("权限错误", ReturnCode.E1000004);
 }
else
 {
if (!Getusergraphql(token))
 {
 throw new CustomException("权限错误", ReturnCode.E1000004);
 }
 //GenericIdentity ci = new GenericIdentity(token);
 //ci.Label = "conan1111111";
 //context.HttpContext.User = new GenericPrincipal(ci, );
 }
 }
else
 {
 throw new CustomException("权限错误", ReturnCode.E1000004);
 }

 base.OnActionExecuting(context);
 }

至此,我们完成了jwt的校验流程。

posted on   漫思  阅读(202)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2017-03-01 nodejs对mongodb数据库的增删改查操作(转载)
2017-03-01 Jade教程

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示