.net 验证jwt的同时取出负载部分
电脑版发表于:2020/1/26 19:11
验证的同时直接获取负载部分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; }