排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术
分类:
NET
验证的同时直接获取负载部分PayLoad,验证成功了难得再取一次
/// <summary> /// 验证的同时直接获取负载部分PayLoad,验证成功了难得再取一次 /// </summary> /// <param name="encodeJwt"></param> /// <param name="validatePayLoad"></param> /// <returns></returns> public bool ValidatePayLoad(string encodeJwt,out Dictionary<string, string> outpayLoad, Func<Dictionary<string, string>, bool> validatePayLoad = null) { outpayLoad = null; var success = true; var jwtArr = encodeJwt.Split('.'); if (jwtArr.Length < 3)//数据格式都不对直接pass { return false; } //var header = JsonConvert.DeserializeObject<Dictionary<string, string>>(Base64UrlEncoder.Decode(jwtArr[0])); var payLoad = JsonConvert.DeserializeObject<Dictionary<string, string>>(Base64UrlEncoder.Decode(jwtArr[1])); //在配置文件中取出来的签名秘钥 var hs256 = new HMACSHA256(Encoding.ASCII.GetBytes(_options.Value.IssuerSigningKey)); //验证签名是否正确(把用户传递的签名部分取出来和服务器生成的签名匹配即可) success = success && string.Equals(jwtArr[2], Base64UrlEncoder.Encode(hs256.ComputeHash(Encoding.UTF8.GetBytes(string.Concat(jwtArr[0], ".", jwtArr[1]))))); if (!success) { return success;//签名不正确直接返回 } //其次验证是否在有效期内(也应该必须) var now = ToUnixEpochDate(DateTime.UtcNow); success = success && (now >= long.Parse(payLoad["nbf"].ToString()) && now < long.Parse(payLoad["exp"].ToString())); //不需要自定义验证不传或者传递null即可 if (validatePayLoad == null) return true; //再其次 进行自定义的验证 success = success && validatePayLoad(payLoad); outpayLoad = payLoad; return success; }
使用如下:
Dictionary<string, string> outpayLoad; ITokenHelper tokenHelper = HttpContext.RequestServices.GetService(typeof(ITokenHelper)) as ITokenHelper; //验证jwt bool isValidate = tokenHelper.ValidatePayLoad(token,out outpayLoad, a => a["iss"] == "i" && a["aud"] == "xj"); if (isValidate==false) { ViewBag.islogin = "false"; HttpContext.Response.Cookies.Delete("token"); return null; }
欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739
评价