您好,登錄后才能下訂單哦!
怎么在.net4.0中實現IdentityServer4客戶端JWT解密?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
public static IDictionary<string, object> DecodeJWT(string jwttoken,string key) { //從/.well-known/openid-configuration路徑獲取jwks_uri var webClient = new WebClient(); var endpoint = "http://localhost:5000/.well-known/openid-configuration"; var json = webClient.DownloadString(endpoint); JObject metadata = JsonConvert.DeserializeObject<JObject>(json); var jwksUri = metadata["jwks_uri"].ToString(); //從jwks_uri獲取keys json = webClient.DownloadString(jwksUri); var keys = JsonConvert.DeserializeObject<CustomJWKs>(json); //從jwt獲取頭部kid,并從keys中找到匹配kid的key string[] tokenParts = jwttoken.Split('.'); byte[] bytes = FromBase64Url(tokenParts[0]); string head= Encoding.UTF8.GetString(bytes); string kid = JsonConvert.DeserializeObject<JObject>(head)["kid"].ToString(); var defaultkey=keys.keys.Where(t => t.kid == kid).FirstOrDefault(); if(defaultkey==null) { throw new Exception("未找到匹配的kid"); } //jwt解密 return RS256Decode(jwttoken, key, defaultkey.e, defaultkey.n); } public static IDictionary<string, object> RS256Decode(string token, string secret, string exponent,string modulus) { try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); RSAlgorithmFactory rS256Algorithm = new RSAlgorithmFactory(() => { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters( new RSAParameters() { Modulus = FromBase64Url(modulus), Exponent = FromBase64Url(exponent) }); byte[] rsaBytes = rsa.ExportCspBlob(true); X509Certificate2 cert = new X509Certificate2(rsaBytes); return cert; }); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, rS256Algorithm); var json = decoder.DecodeToObject(token, secret, verify: false); return json; } catch (TokenExpiredException) { throw new Exception("token已過期"); //Console.WriteLine("Token has expired"); //return null; } catch (SignatureVerificationException) { throw new Exception("token驗證失敗"); //Console.WriteLine("Token has invalid signature"); //return null; } } public static byte[] FromBase64Url(string base64Url) { string padded = base64Url.Length % 4 == 0 ? base64Url : base64Url + "====".Substring(base64Url.Length % 4); string base64 = padded.Replace("_", "/") .Replace("-", "+"); return Convert.FromBase64String(base64); }
看完上述內容,你們掌握怎么在.net4.0中實現IdentityServer4客戶端JWT解密的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。