JWT 帮助类 JWTHelper
生活随笔
收集整理的這篇文章主要介紹了
JWT 帮助类 JWTHelper
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
JWTPlayloadInfo.cs 代碼如下:
/// <summary>/// JWT載荷實(shí)體/// </summary>public sealed class JWTPlayloadInfo{/// <summary>/// jwt簽發(fā)者/// </summary>public string iss { get; set; } = "Berry.Service";/// <summary>/// jwt所面向的用戶(hù) UserId/// </summary>public string sub { get; set; } = "";/// <summary>/// 接收jwt的一方 /// </summary>public string aud { get; set; } = "";/// <summary>/// jwt的簽發(fā)時(shí)間/// </summary>public string iat { get; set; } = Utils.FormatDate(DateTime.Now, "1");/// <summary>/// jwt的過(guò)期時(shí)間,這個(gè)過(guò)期時(shí)間必須要大于簽發(fā)時(shí)間.默認(rèn)60分鐘/// </summary>public string exp { get; set; }public TimeSpan daySpan { get; set; }/// <summary>/// 定義在什么時(shí)間之前,該jwt都是不可用的./// </summary>public int nbf { get; set; }public string ip { get; set; }/// <summary>/// jwt的唯一身份標(biāo)識(shí),主要用來(lái)作為一次性token,從而回避重放攻擊。/// </summary>public string jti { get; set; } = Utils.GetGUID().ToString();/// <summary>/// 用戶(hù)ID。自定義字段/// </summary>public string userid { get; set; }/// <summary>/// 擴(kuò)展字段。自定義字段/// </summary>public string extend { get; set; }/// <summary>/// 自定義對(duì)象/// </summary>public object data { get; set; }public string token { get; set; }}JWTHelper.cs 代碼如下:
using Currency.Redis; using JWT; using JWT.Algorithms; using JWT.Serializers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace Currency.Common {/// <summary>/// JWT操作幫助類(lèi)/// </summary>public sealed class JWTHelper{/// <summary>/// 簽發(fā)Token/// </summary>/// <param name="playload">載荷</param>/// <returns></returns>public static string GetToken(JWTPlayloadInfo playload){string token = String.Empty;IJwtAlgorithm algorithm = new HMACSHA256Algorithm();IJsonSerializer serializer = new JsonNetSerializer();IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);//設(shè)置過(guò)期時(shí)間DateTime time = DateTime.Now.Add(playload.daySpan);if (!string.IsNullOrEmpty(playload.iat)){var iat = DateTime.Now;try{iat = DateTime.Parse(playload.iat);}catch (Exception){iat = DateTime.Now;}time = iat.Add(playload.daySpan);}playload.exp = Utils.GetTimeStamp(time);//獲取私鑰string secret = GetSecret();if (!string.IsNullOrEmpty(playload.sub)){token = encoder.Encode(playload, secret);}return token;}/// <summary>/// Token校驗(yàn)/// </summary>/// <param name="token"></param>/// <returns></returns>public static JWTPlayloadInfo CheckToken(string token){try{if (string.IsNullOrEmpty(token)) return null;IJsonSerializer serializer = new JsonNetSerializer();IDateTimeProvider provider = new UtcDateTimeProvider();IJwtValidator validator = new JwtValidator(serializer, provider);IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);//獲取私鑰string secret = GetSecret();JWTPlayloadInfo playloadInfo = decoder.DecodeToObject<JWTPlayloadInfo>(token, secret, true);if (playloadInfo != null){if (!string.IsNullOrEmpty(playloadInfo.sub)){var cacheToken = RedisHelper.StringGet($"user:login:{playloadInfo.sub}:{playloadInfo.jti}");return Check(playloadInfo, cacheToken, token) ? playloadInfo : null;}}}catch (Exception){return null;}return null;}private static bool Check(JWTPlayloadInfo info, string cacheToken, string token){if (string.IsNullOrEmpty(cacheToken)) return false;if (string.IsNullOrEmpty(token)) return false;if (!cacheToken.Equals(token)) return false;//Token過(guò)期DateTime exp = Utils.GetTime(info.exp);if (DateTime.Now > exp){if (!string.IsNullOrEmpty(info.sub)){RedisHelper.KeyDelete($"user:login:{info.sub}:{info.jti}");}return false;}return true;}/// <summary>/// 獲取私鑰/// </summary>/// <returns></returns>private static string GetSecret(){//TODO 從文件中去讀真正的私鑰return "eyJpc3MiOiJCZXJyeS5TZXJ2aWNlIiwic3ViIjoiMTgyODQ1OTQ2MTkiLCJhdWQiOiJndWVzdCIsImlhdCI6IjE1MzEzODE5OTgiLCJleHAiOiIxNTMxMzg5MTk4IiwibmJmIjowLCJqdGkiOiI1YzdmN2ZhM2E4ODVlODExYTEzNTQ4ZDIyNGMwMWQwNSIsInVzZXJpZCI6bnVsbCwiZXh0ZW5kIjpudWxsfQ";}}}其中用到了?RedisHelper,請(qǐng)參考另一篇文章?https://blog.csdn.net/u013608482/article/details/88397789
總結(jié)
以上是生活随笔為你收集整理的JWT 帮助类 JWTHelper的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: k8s之QoS简介
- 下一篇: DownloadHelper使用教程