using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace ERP.Framework.Security
{
public static class TokenHelper
{
///
/// 创建Token
///
/// 密匙
/// 用户Id
/// Token 过期时间
/// tokenId
///
public static string CreateToken(
string securityKey
, long userId
, string userName
, int expires
, out string tokenId)
{
tokenId = Guid.NewGuid().ToString();
var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.UniqueName,tokenId),
new Claim(JwtRegisteredClaimNames.NameId,userId.ToString()),
new Claim(ClaimTypes.Name,userName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
var token = new JwtSecurityToken(
issuer: "ERP",
audience: "ERP",
claims: claims,
notBefore: DateTime.Now,
expires: DateTime.Now.AddMinutes(expires),
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public static bool ValidateToken(
string? token,
string secutityKey)
{
if (token == null)
{
return false;
}
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
ValidateIssuer = true, //是否验证Issuer
ValidateAudience = true, //是否验证Audience
ValidateLifetime = true, //是否验证失效时间---默认添加300s后过期
ValidateIssuerSigningKey = true, //是否验证SecurityKey
ClockSkew = TimeSpan.Zero,
ValidIssuer = "ERP",
ValidAudience = "ERP",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secutityKey)),
};
try
{
tokenHandler.ValidateToken(token, validationParameters, out _);
return true;
}
catch
{
return false;
}
}
public static IEnumerable GetClaims(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
var jwtToken = tokenHandler.ReadJwtToken(token);
return jwtToken.Claims;
}
}
}