You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
3.1 KiB
85 lines
3.1 KiB
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
|
|
namespace Shentun.PeisReport.Api.Jwt
|
|
{
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public class JwtHelper
|
|
{
|
|
|
|
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public JwtHelper()
|
|
{
|
|
|
|
}
|
|
/// <summary>
|
|
/// 获取JWT令牌
|
|
/// </summary>
|
|
/// <param name="claims"></param>
|
|
/// <returns></returns>
|
|
public string GetJwt(IEnumerable<Claim> claims)
|
|
{
|
|
var dateTime = DateTime.UtcNow;//世界时间
|
|
//秘钥
|
|
var jwtConfig = new JwtConfig();
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey));
|
|
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
// 过期时间
|
|
double expMin= jwtConfig.WebExpiration;
|
|
|
|
DateTime expTime = dateTime.AddMinutes(expMin);
|
|
var jwt = new JwtSecurityToken(
|
|
issuer: jwtConfig.Issuer,//颁发者
|
|
audience: jwtConfig.Audience,//颁发给
|
|
claims: claims, //声明集合
|
|
notBefore: dateTime,//生效时间,这里必须使用世界时间
|
|
expires: expTime,//过期时间,这里必须使用世界时间
|
|
signingCredentials: creds);
|
|
|
|
var jwtHandler = new JwtSecurityTokenHandler().WriteToken(jwt);
|
|
|
|
return jwtHandler;
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 获取TokenValidationParameters
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public TokenValidationParameters GetTokenValidationParameters()
|
|
{
|
|
var jwtConfig = new JwtConfig();
|
|
TokenValidationParameters tokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
ValidIssuer = jwtConfig.Issuer,//颁发者
|
|
ValidAudience = jwtConfig.Audience,//颁发给
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey)),
|
|
|
|
/***********************************TokenValidationParameters的参数默认值***********************************/
|
|
RequireSignedTokens = true,
|
|
// SaveSigninToken = false,
|
|
// ValidateActor = false,
|
|
// 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
|
|
ValidateAudience = true,//颁发给验证
|
|
ValidateIssuer = true,//颁发者验证
|
|
ValidateIssuerSigningKey = true,
|
|
// 是否要求Token的Claims中必须包含 Expires
|
|
RequireExpirationTime = true,
|
|
// 允许的服务器时间偏移量
|
|
ClockSkew = TimeSpan.FromSeconds(300),
|
|
// 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
|
|
ValidateLifetime = true
|
|
};
|
|
return tokenValidationParameters;
|
|
}
|
|
|
|
}
|
|
}
|