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;
}
}