You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

169 lines
5.9 KiB
C#

12 months ago
using DS.Module.Core.Extensions;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace DS.Module.Core;
public class JwtHelper
{
/// <summary>
/// 生成JWT字符串
/// </summary>
/// <param name="Jti"></param>
/// <returns></returns>
public static string GetJWT(string Jti)
{
DateTime utc = DateTime.UtcNow;
10 months ago
string iss = AppSetting.app(new string[] { "JwtSettings", "Issuer" });
string aud = AppSetting.app(new string[] { "JwtSettings", "Audience" });
string secret = AppSetting.app(new string[] { "JwtSettings", "SecretKey" });
12 months ago
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Jti, Jti),
// 令牌颁发时间
new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
// 过期时间 2小时
new Claim(JwtRegisteredClaimNames.Exp,
$"{new DateTimeOffset(DateTime.Now).AddMinutes(120).ToUnixTimeSeconds()}"),
new Claim(JwtRegisteredClaimNames.Iss, iss), // 签发者
new Claim(JwtRegisteredClaimNames.Aud, aud) // 接收者
};
// 密钥
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var tokenHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwt = new JwtSecurityToken(
issuer: iss,
claims: claims, // 声明的集合
10 months ago
//expires: .AddSeconds(36), // token的有效时间
12 months ago
signingCredentials: creds
);
var handler = new JwtSecurityTokenHandler();
// 生成 jwt字符串
var strJWT = handler.WriteToken(jwt);
return strJWT;
}
10 months ago
/// <summary>
/// 生成Token
/// </summary>
/// <param name="data"></param>
/// <param name="isRefresh">是否刷新</param>
10 months ago
/// <param name="isClient">是否客户端</param>
10 months ago
/// <returns></returns>
10 months ago
public static string Encrypt(JwtTokenModel data, bool isRefresh = false,bool isClient = false)
12 months ago
{
DateTime utc = DateTime.UtcNow;
10 months ago
string iss = AppSetting.app(new string[] { "JwtSettings", "Issuer" });
string aud = AppSetting.app(new string[] { "JwtSettings", "Audience" });
string secret = AppSetting.app(new string[] { "JwtSettings", "SecretKey" });
12 months ago
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Jti, data.Uid),
// 令牌颁发时间
new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
// 过期时间 2小时
new Claim(JwtRegisteredClaimNames.Exp,
10 months ago
isRefresh
? $"{new DateTimeOffset(DateTime.Now).AddMinutes(150).ToUnixTimeSeconds()}" :$"{new DateTimeOffset(DateTime.Now).AddMinutes(120).ToUnixTimeSeconds()}"),
12 months ago
new Claim(JwtRegisteredClaimNames.Iss, iss), // 签发者
10 months ago
new Claim(JwtRegisteredClaimNames.Aud, aud), // 接收者
// new Claim("OrgId", data.OrgId), // 公司ID
12 months ago
10 months ago
new Claim("TenantId", data.TenantId), // 租户ID
10 months ago
12 months ago
};
10 months ago
// 添加机构信息
if (isClient)
{
claims.Add(new Claim("OrgId", data.OrgId));// 机构ID
}
12 months ago
// 密钥
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var tokenHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwt = new JwtSecurityToken(
issuer: iss,
claims: claims, // 声明的集合
10 months ago
//expires: .AddSeconds(36), // token的有效时间
12 months ago
signingCredentials: creds
);
var handler = new JwtSecurityTokenHandler();
// 生成 jwt字符串
var strJWT = handler.WriteToken(jwt);
return strJWT;
}
/// <summary>
/// 解析
/// </summary>
/// <param name="jwtStr"></param>
/// <returns></returns>
public static string SerializeJwt(string jwtStr)
{
var jwtHandler = new JwtSecurityTokenHandler();
string userId = string.Empty;
// token校验
if (jwtStr.IsNullOrEmpty() && jwtHandler.CanReadToken(jwtStr))
{
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
userId = jwtToken.Claims.First().Value;
}
10 months ago
12 months ago
return userId;
}
10 months ago
/// <summary>
/// 对jwt字符串 解码
/// </summary>
public static Dictionary<string, string> DecodeJwt(string accessToken)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
var jwtHandler = new JwtSecurityTokenHandler();
// token校验
if (!string.IsNullOrEmpty(accessToken) && jwtHandler.CanReadToken(accessToken))
{
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(accessToken);
var claims = jwtToken.Claims;
foreach (var claim in claims)
{
dic.Add(claim.Type, claim.Value);
}
}
return dic;
}
12 months ago
/// <summary>
/// token实体
/// </summary>
public class JwtTokenModel
{
/// <summary>
/// Id
/// </summary>
public string Uid { get; set; }
/// <summary>
/// GID
/// </summary>
public Guid? GID { get; set; }
/// <summary>
10 months ago
/// 机构ID
12 months ago
/// </summary>
10 months ago
public string OrgId { get; set; }
12 months ago
/// <summary>
/// 租户ID
/// </summary>
public string TenantId { get; set; }
}
}