.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的校验流程。
漫思
分类:
C#.NET
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2017-03-01 nodejs对mongodb数据库的增删改查操作(转载)
2017-03-01 Jade教程