123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- using Microsoft.AspNetCore.Authentication;
- using Microsoft.AspNetCore.Authentication.Cookies;
- using Microsoft.AspNetCore.Http;
- using NetTaste;
- using OASystem.API.OAMethodLib.JuHeAPI;
- using OASystem.Domain.Dtos.Business;
- using SqlSugar.Extensions;
- using System.IdentityModel.Tokens.Jwt;
- using System.Security.Claims;
- using static NPOI.HSSF.Util.HSSFColor;
- namespace OASystem.API.OAMethodLib
- {
- public class JWTHelper
- {
- public class JwtHelper
- {
- private readonly static IHttpContextAccessor _httpContext = AutofacIocManager.Instance.GetService<IHttpContextAccessor>();
- /// <summary>
- /// 颁发JWT字符串
- /// </summary>
- /// <param name="tokenModel"></param>
- /// <returns></returns>
- public static async Task<string> IssueJwtAsync(TokenModelJwt tokenModel)
- {
- // appsettign.json 操作类
- string iss = "OASystem.com";
- string aud = "OASystem.com";
- string secret = AppSettingsHelper.Get("JwtSecurityKey");
- var claims = new List<Claim>
- {
- /*
- * 特别重要:
- 1、这里将用户的部分信息,比如 uid 存到了Claim 中,如果你想知道如何在其他地方将这个 uid从 Token 中取出来,请看下边的SerializeJwt() 方法
- 2、你也可以研究下 HttpContext.User.Claims ,具体的你可以看看 Policys/PermissionHandler.cs 类中是如何使用的。
- */
- new Claim(JwtRegisteredClaimNames.Jti, tokenModel.UserId.ToString()),
- new Claim(JwtRegisteredClaimNames.Name, tokenModel.UserName),
- new Claim(JwtRegisteredClaimNames.FamilyName, tokenModel.Department),
- //new Claim("UserId", tokenModel.UserId.ToString()),
- new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
- new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
- //过期时间,目前是过期7200秒,可自定义,注意JWT有自己的缓冲过期时间
- new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(7200)).ToUnixTimeSeconds()}"),
- new Claim(JwtRegisteredClaimNames.Iss,iss),
- new Claim(JwtRegisteredClaimNames.Aud,aud),
-
- //new Claim(ClaimTypes.Role,tokenModel.Role),//为了解决一个用户多个角色(比如:Admin,System),用下边的方法
- };
- // 可以将一个用户的多个角色全部赋予;
- claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
- //秘钥 (SymmetricSecurityKey 对安全性的要求,密钥的长度太短会报出异常)
- var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
- var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
- var jwt = new JwtSecurityToken(
- issuer: iss,
- claims: claims,
- signingCredentials: creds
- //,expires:DateTime.Now.AddMinutes(1)
- );
- var jwtHandler = new JwtSecurityTokenHandler();
- var encodedJwt = jwtHandler.WriteToken(jwt);
- return encodedJwt;
- }
- /// <summary>
- /// 解析
- /// </summary>
- /// <param name="jwtStr"></param>
- /// <returns></returns>
- public static TokenModelJwt SerializeJwt(string jwtStr)
- {
- if (string.IsNullOrEmpty(jwtStr)) return null;
- jwtStr = jwtStr.Replace("Bearer ", "");
- if (string.IsNullOrEmpty(jwtStr)) return null;
- var jwtHandler = new JwtSecurityTokenHandler();
- JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);;
- object role,userName,department;
- try
- {
- jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
- jwtToken.Payload.TryGetValue("family_name", out department);
- jwtToken.Payload.TryGetValue("name", out userName);
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- throw;
- }
- var tm = new TokenModelJwt
- {
- UserId = (jwtToken.Id).ObjToInt(),
- UserName = userName != null ? userName.ObjToString() : "",
- Department = department != null ? department.ObjToString() : "",
- Role = role != null ? role.ObjToString() : "",
- };
- return tm;
- }
- }
- /// <summary>
- /// 令牌
- /// </summary>
- public class TokenModelJwt
- {
- /// <summary>
- /// Id
- /// </summary>
- public int UserId { get; set; }
- public string UserName { get; set; }
- public string Department { get; set; } = "信息部";
- public string Role { get; set; } = "Admin";
- /// <summary>
- /// 过期时间,默认过期7200秒
- /// 注意JWT有自己的缓冲过期时间
- /// </summary>
- public int ExpirationTime { get; set; } = 7200;
- }
- }
- }
|