12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- using Microsoft.IdentityModel.Tokens;
- using System.IdentityModel.Tokens.Jwt;
- using System.Security.Claims;
- using System.Text;
- namespace ERP.Framework.Security
- {
- public static class TokenHelper
- {
- /// <summary>
- /// 创建Token
- /// </summary>
- /// <param name="securityKey">密匙</param>
- /// <param name="userId">用户Id</param>
- /// <param name="expires">Token 过期时间</param>
- /// <param name="tokenId">tokenId</param>
- /// <returns></returns>
- 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<Claim> GetClaims(string token)
- {
- var tokenHandler = new JwtSecurityTokenHandler();
- var jwtToken = tokenHandler.ReadJwtToken(token);
- return jwtToken.Claims;
- }
- }
- }
|