1
This commit is contained in:
59
Gatedge.ScanCode/Utils/JwtUtils.cs
Normal file
59
Gatedge.ScanCode/Utils/JwtUtils.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using Gatedge.K3Cloud.Utils.Model.K3Request;
|
||||
using Gatedge.ScanCode.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace Gatedge.ScanCode.Utils;
|
||||
|
||||
/// <summary>
|
||||
/// JWT帮助类
|
||||
/// </summary>
|
||||
public class JwtUtils
|
||||
{
|
||||
private readonly JwtOption _option;
|
||||
/// <summary>
|
||||
/// JwtUtils,option是从ICO容器中拿到的对象
|
||||
/// </summary>
|
||||
public JwtUtils(JwtOption option)
|
||||
{
|
||||
_option = option;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建Token
|
||||
/// </summary>
|
||||
/// <param name="loginInfo"></param>
|
||||
/// <returns></returns>
|
||||
public string CreateToken(LoginInfo loginInfo)
|
||||
{
|
||||
// 1. 定义需要使用到的Claims
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim("UserName", loginInfo.UserName),
|
||||
new Claim("LCId", loginInfo.LCId.ToString()),
|
||||
new Claim("ServerUrl", loginInfo.ServerUrl),
|
||||
new Claim("DBID", loginInfo.DBID),
|
||||
new Claim("orgNum", loginInfo.OrgNum),
|
||||
};
|
||||
// 2. 从 appsettings.json 中读取SecretKey
|
||||
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_option.SecretKey));
|
||||
// 3. 选择加密算法
|
||||
var algorithm = SecurityAlgorithms.HmacSha256;
|
||||
// 4. 生成Credentials
|
||||
var signingCredentials = new SigningCredentials(secretKey, algorithm);
|
||||
// 5. 根据以上,生成token
|
||||
var jwtSecurityToken = new JwtSecurityToken(
|
||||
_option.Issuer, //Issuer
|
||||
_option.Audience, //Audience
|
||||
claims, //Claims,
|
||||
DateTime.Now, //notBefore
|
||||
DateTime.Now.AddSeconds(_option.FailureTime), //expires
|
||||
signingCredentials //Credentials
|
||||
);
|
||||
// 6. 将token变为string
|
||||
var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
|
||||
return token;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user