71 lines
2.2 KiB
C#
71 lines
2.2 KiB
C#
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Net.Http;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
|
|
namespace YLErp.Helpers
|
|
{
|
|
/// <summary>
|
|
/// 用户认证帮助类
|
|
/// </summary>
|
|
public class AuthHelper
|
|
{
|
|
public const string CookieAuthType = "yc_identity";
|
|
|
|
public const string JwtAuthType = "yc_mapi";
|
|
|
|
public const int ExpireInSeconds = 3600 * 10; //10个小时
|
|
|
|
public const string JwtIssuer = "yilian";
|
|
|
|
public const string JwtAudience = "yilian";
|
|
|
|
public const string JwtSecretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrkzI1NiJ9eyJjbGFTT";
|
|
|
|
public const string JwtUserToken = "###jwt###";
|
|
|
|
/// <summary>
|
|
/// 创建jwt令牌
|
|
/// </summary>
|
|
public static string CreateJwtToken(ClaimsIdentity identity)
|
|
{
|
|
var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtSecretKey));
|
|
|
|
var tokenDescriptor = new SecurityTokenDescriptor
|
|
{
|
|
Subject = new ClaimsIdentity(identity),
|
|
Expires = DateTime.UtcNow.AddSeconds(ExpireInSeconds),
|
|
Issuer = JwtIssuer,
|
|
Audience = JwtAudience,
|
|
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature)
|
|
};
|
|
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
|
|
var token = tokenHandler.CreateToken(tokenDescriptor);
|
|
|
|
return tokenHandler.WriteToken(token);
|
|
}
|
|
|
|
public static string CreateJwtToken2(ClaimsIdentity identity)
|
|
{
|
|
var key = new SymmetricSecurityKey(Convert.FromBase64String(JwtSecretKey));
|
|
|
|
var tokenDescriptor = new SecurityTokenDescriptor
|
|
{
|
|
Subject = new ClaimsIdentity(identity),
|
|
Expires = DateTime.UtcNow.AddSeconds(ExpireInSeconds),
|
|
IssuedAt = DateTime.Now,
|
|
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512)
|
|
};
|
|
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
|
|
var token = tokenHandler.CreateToken(tokenDescriptor);
|
|
|
|
return tokenHandler.WriteToken(token);
|
|
}
|
|
}
|
|
}
|