(二)jwt的生成以及其他辅助方法(通过token获取过期时间,是否过期,用户id)等


public class JwtHelper
{
//生成jwt
public static string IssueJwt()
{
string exp = $"{new DateTimeOffset(DateTime.Now.AddMinutes(120)).ToUnixTimeSeconds()}";
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Jti,"1"),//编号,一般存用户id
new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),//签发时间
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,//生效时间,在此之前是无效的
//JWT过期时间
new Claim (JwtRegisteredClaimNames.Exp,exp),//过期时间
new Claim(JwtRegisteredClaimNames.Iss,"pms.core.owner"),//签发人
new Claim(JwtRegisteredClaimNames.Aud,"pms.core"),//受众
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("BB3647441FFA4B5DB4E64A29B53CE525"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
JwtSecurityToken securityToken = new JwtSecurityToken(issuer: "pms.core.owner", claims: claims, signingCredentials: creds);
string jwt = new JwtSecurityTokenHandler().WriteToken(securityToken);
return jwt;
}
//获取过期时间
public static DateTime GetExp(string jwtStr)
{
var jwtHandler = new JwtSecurityTokenHandler();
JwtSecurityToken securityToken = jwtHandler.ReadJwtToken(jwtStr);
DateTime expDate = (securityToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0).GetInt().GetTimeSpmpToDate();
return expDate;
}
//判断是否过时
public static bool IsExp(string jwtStr)
{
return GetExp(jwtStr) < DateTime.Now;
}
//获取编号id,因为编号id的Jti的值是存的用户id,所以取值结果就是用户的id
public static string GetUserId(string jwtStr)
{
try
{
return new JwtSecurityTokenHandler().ReadJwtToken(jwtStr).Id;
}
catch (Exception)
{

return string.Empty;
}
}

}
public static class Exeprission
{
//object转int
public static int GetInt(this object obj)
{
if (obj == null)
return 0;
int _number = 0;
bool reslut = Int32.TryParse(obj.ToString(), out _number);
return _number;

}
// 时间戳转换成日期
private static DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0);
private static long longTime = 621355968000000000;
private static int samllTime = 10000000;
public static DateTime GetTimeSpmpToDate(this object timeStamp)
{
if (timeStamp == null) return dateStart;
DateTime dateTime = new DateTime(longTime + Convert.ToInt64(timeStamp) * samllTime, DateTimeKind.Utc).ToLocalTime();
return dateTime;
}

}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM