JWTHelper
public class JWTHelper { public static string IssueJwt(TokenModelJwt tokenModel) { string iss = AppSettings.app(new string[] { "Audience", "Issuer" }); string aud = AppSettings.app(new string[] { "Audience", "Audience" }); string secret = AppSettings.app(new string[] { "Audience", "Secret" }); var claims = new List<Claim> { new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString()), new Claim(JwtRegisteredClaimNames.Iat,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"), new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"), new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(1000)).ToUnixTimeSeconds()}"), new Claim(ClaimTypes.Expiration,DateTime.Now.AddSeconds(1000).ToString()), new Claim(JwtRegisteredClaimNames.Iss,iss), new Claim(JwtRegisteredClaimNames.Aud,aud) }; claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); 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); var jwtHandler = new JwtSecurityTokenHandler(); var encodedJwt = jwtHandler.WriteToken(jwt); return encodedJwt; } public static TokenModelJwt SerializeJwt(string jwtStr) { var jwtHandler = new JwtSecurityTokenHandler(); TokenModelJwt tokenModelJwt = new TokenModelJwt(); if (!string.IsNullOrEmpty(jwtStr) && jwtHandler.CanReadToken(jwtStr)) { JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr); object role; jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role); tokenModelJwt = new TokenModelJwt { Uid = Convert.ToInt32(jwtToken.Id), Role = role == null ? "" : role.ToString() }; } return tokenModelJwt; } }
public class TokenModelJwt { public int Uid { get; set; } public string Role { get; set; } public string Work { get; set; } }