2025-06-06 14:57:20 +08:00

112 lines
4.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using YD_WeChatApplet.Commons;
using YD_WeChatApplet.Commons.Utils;
namespace YD_WeChatApplet.Api.Utilities
{
public class JwtHelper
{
/// <summary>
/// 生成JWT
/// </summary>
/// <param name="serInfo"></param>
/// <returns></returns>
public static string IssueJwt(UserInfoDto userInfo)
{
string exp = $"{new DateTimeOffset(DateTime.Now.AddMinutes(Convert.ToInt32(AppSettings.ExpMinutes))).ToUnixTimeSeconds()}";
var claims = new List<Claim>
{
//new Claim(ClaimTypes.Role,userInfo.Role_Id ),
new Claim(JwtRegisteredClaimNames.Sid,userInfo.SchoolCode.ToString()??""),
new Claim(JwtRegisteredClaimNames.Typ,userInfo.Role_Id.ToString() ??""),
new Claim(JwtRegisteredClaimNames.Jti,userInfo.User_Id.ToString()??""),
new Claim(JwtRegisteredClaimNames.Nickname,userInfo.UserTrueName??""),
new Claim(JwtRegisteredClaimNames.Name,userInfo.UserName??""),
new Claim(JwtRegisteredClaimNames.PhoneNumber,userInfo.PhoneNo??""),
new Claim(JwtRegisteredClaimNames.Azp,userInfo.UserNo??""),
new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
//JWT过期时间
//验证是否过期 从User读取过期 时间再将时间戳转换成日期如果时间在半个小时内即将过期通知前台刷新JWT
//int val= HttpContext.User.Claims.Where(x => x.Type == JwtRegisteredClaimNames.Exp).FirstOrDefault().Value;
//new DateTime(621355968000000000 + (long)val* (long)10000000, DateTimeKind.Utc).ToLocalTime()
//默认设置jwt过期时间120分钟
new Claim (JwtRegisteredClaimNames.Exp,exp),
new Claim(JwtRegisteredClaimNames.Iss,AppSettings.Secret.Issuer),
new Claim(JwtRegisteredClaimNames.Aud,AppSettings.Secret.Audience),
};
//秘钥16位
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.Secret.JWT));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
JwtSecurityToken securityToken = new JwtSecurityToken(issuer: AppSettings.Secret.Issuer, claims: claims, signingCredentials: creds);
string jwt = new JwtSecurityTokenHandler().WriteToken(securityToken);
return jwt;
}
/// <summary>
/// 解析
/// </summary>
/// <param name="jwtStr"></param>
/// <returns></returns>
public static UserInfoDto SerializeJwt(string jwtStr)
{
var jwtHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
UserInfoDto userInfo = new UserInfoDto
{
User_Id = Convert.ToInt32(jwtToken.Payload["jti"]),
Role_Id = Convert.ToInt32(jwtToken.Payload["typ"]),
UserName = jwtToken.Payload["name"]?.ToString(),
PhoneNo = jwtToken.Payload["phone_number"]?.ToString(),
SchoolCode = jwtToken.Payload["sid"]?.ToString(),
UserTrueName = jwtToken.Payload["nickname"]?.ToString(),
UserNo = jwtToken.Payload["azp"]?.ToString(),
};
return userInfo;
}
/// <summary>
/// 获取过期时间
/// </summary>
/// <param name="jwtStr"></param>
/// <returns></returns>
public static DateTime GetExp(string jwtStr)
{
var jwtHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
DateTime expDate = (jwtToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0).GetInt().GetTimeSpmpToDate();
return expDate;
}
public static bool IsExp(string jwtStr)
{
return GetExp(jwtStr) < DateTime.Now;
}
public static int GetUserId(string jwtStr)
{
try
{
if (jwtStr.IsNullOrEmpty()) return 0;
jwtStr = jwtStr.Replace("Bearer ", "");
return new JwtSecurityTokenHandler().ReadJwtToken(jwtStr).Id.GetInt();
}
catch
{
return 0;
}
}
}
}