.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 2023-03-01 10:51  漫思  阅读(261)  评论(0)    收藏  举报

导航