using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace Demo { /// <summary> /// Token处理类 /// </summary> public class Token { /// <summary> /// 生成JWT /// </summary> /// <param name="user"></param> /// <param name="secretKey"></param> /// <param name="issuer"></param> /// <param name="audience"></param> /// <param name="expiryMinutes"></param> /// <returns></returns> public static string GenerateJwt(User user, string secretKey, string issuer, string audience, int expiryMinutes) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(ClaimTypes.Name, user.Username), new Claim(ClaimTypes.Role, user.Group.ToString()), }; var token = new JwtSecurityToken( issuer: issuer, audience: audience, claims: claims, expires: DateTime.UtcNow.AddMinutes(expiryMinutes), signingCredentials: credentials ); var tokenHandler = new JwtSecurityTokenHandler(); var jwtToken = tokenHandler.WriteToken(token); return jwtToken; } } }
翻译
搜索
复制
标签:string,C#,JWT,System,生成,using,var,new From: https://www.cnblogs.com/smartnn/p/18109952