C# 生成JWT的示例代码
作者:Mr_Xul
这篇文章主要介绍了C# 生成JWT的示例代码,需要的朋友可以参考下
C# 生成JWT的代码如下所示:
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;
}
}
}到此这篇关于C# 生成JWT的示例代码的文章就介绍到这了,更多相关C# 生成JWT内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
