/// <summary> /// 根据jwtToken 获取实体 /// </summary> /// <param name="token">jwtToken</param> /// <returns></returns> public static string GetJwtDecode(string token) { try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); //token为之前生成的字符串 var userInfo = decoder.DecodeToObject(token, secret, verify: true); //此处json为IDictionary<string, object> 类型 string username = userInfo["username"].ToString(); //可获取当前用户名 DateTime timeout = (DateTime)userInfo["timeout"]; //获取token过期时间 if (timeout < DateTime.Now) { throw new TokenExpiredException("Token过期,请重新登陆"); } userInfo.Remove("timeout"); return("OK"); } catch (TokenExpiredException tokenEx) { return("[Error]Token过期:--" + tokenEx.Message); } catch (SignatureVerificationException tokenEx) { return("[Error] 无效的Token:--" + tokenEx.Message); } catch (Exception ex) { return("[Error]:" + ex.Message); } }
public static Dictionary <string, object> EnDecode(string jwtStr, string key = null) { if (string.IsNullOrEmpty(key)) { key = Key; } try { 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); var json = decoder.Decode(jwtStr, key, verify: true); //把一个字符串反向生成对应的对象内容 var reslut = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); if ((DateTime)reslut["timeout"] < DateTime.Now) { throw new Exception("jwt已经过期,请重新登陆"); } reslut.Remove("timeout"); return(reslut); } catch (TokenExpiredException) { throw; } catch (SignatureVerificationException) { throw; } }
public static IDictionary <string, object> Decode(string token, string secret, string salt, int iter) { IDictionary <string, object> rdict = new Dictionary <string, object>(); try { 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, new HMACSHA256Algorithm()); var dict = decoder.DecodeToObject <IDictionary <string, object> >(token, NewKey(secret, salt, iter), verify: true); return(dict); } catch (TokenExpiredException) { rdict["Error"] = "Token has expired"; return(rdict); } catch (SignatureVerificationException) { rdict["Error"] = "Token has invalid signature"; return(rdict); } }
public void Decode(HttpRequest request) { string token = Request.Headers["Authorization"]; if (string.IsNullOrEmpty(token)) { HttpContext.Response.StatusCode = 401; throw new ApiException("No Authorization header"); } try { JwtDecoder decoder = Data.JwtDecode(token); Executer = decoder.Id_User; } catch (InvalidToken it) { HttpContext.Response.StatusCode = 401; throw new ApiException(it.Message); } catch (ExpiredToken et) { HttpContext.Response.StatusCode = 401; throw new ApiException(et.Message); } catch (Exception e) { Console.Out.WriteLine(e.Message); HttpContext.Response.StatusCode = 400; throw new ApiException("Unhandeled exception"); } }
public static rs Decode(string token = "") { rs r; var secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk"; try { 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); // var json = decoder.Decode(token, secret, verify: true); JwtLoginModel model = JsonConvert.DeserializeObject <JwtLoginModel>(json); r = rs.T("Ok", model); } catch (TokenExpiredException) { r = rs.F("Token has expired"); } catch (SignatureVerificationException) { r = rs.F("Token has invalid signature"); } return(r); }
public static Token extractPaylod(string _token) { string jsonPayload = ""; Token tokenPayload = null; try { 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 = ConfigurationManager.AppSettings["key"].ToString(); jsonPayload = decoder.Decode(_token, secret, verify: true); tokenPayload = serializer.Deserialize <Token>(jsonPayload); //Console.WriteLine(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); } return(tokenPayload); }
/// <summary> /// Jwt 解密 /// </summary> /// <returns></returns> public static Dictionary <string, object> Decode(string secret, string token) { try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var json = decoder.Decode(token, secret, verify: true); var payload = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); // 去除超时时间 if ((DateTime)payload["timeOut"] < DateTime.Now) { throw new Exception("登录超时,请重新登录"); } payload.Remove("timeOut"); return(payload); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); throw; } catch (SignatureVerificationException) { Console.WriteLine("签名验证失败,数据可能被篡改"); throw; } }
public static Dictionary <string, object> Decode(string jwtStr, string key = null) { if (string.IsNullOrWhiteSpace(key)) { key = Key; } try { IJsonSerializer jsonSerializer = new JsonNetSerializer(); IDateTimeProvider dateTimeProvider = new UtcDateTimeProvider(); IJwtValidator jwtValidator = new JwtValidator(jsonSerializer, dateTimeProvider); IAlgorithmFactory algorithmFactory = new HMACSHAAlgorithmFactory(); IJwtAlgorithm jwtAlgorithm = new HMACSHA256Algorithm(); IBase64UrlEncoder base64UrlEncoder = new JwtBase64UrlEncoder(); IJwtDecoder jwtDecoder = new JwtDecoder(jsonSerializer, jwtValidator, base64UrlEncoder, algorithmFactory); var json = jwtDecoder.Decode(token: jwtStr, key, verify: true); var result = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); if (Convert.ToDateTime(result["timeout"]) < DateTime.Now) { throw new Exception(message: "token已过期请重新登录"); } else { result.Remove(key: "timeout"); } return(result); } catch (TokenExpiredException) { throw; } }
public static ActionOutput ValidateToken(string token) { var secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk"; try { 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); var json = decoder.Decode(token, secret, verify: true); return(new ActionOutput { Message = json, Status = ActionStatus.Successfull }); } catch (TokenExpiredException ex) { return(new ActionOutput { Message = "Token has been expired", Status = ActionStatus.Error }); } catch (SignatureVerificationException) { return(new ActionOutput { Message = "Token has invalid signature", Status = ActionStatus.Error }); } }
private bool IsTokenValid() { try { var secret = WebConfigurationManager.AppSettings.Get("JwtSecretKey"); var serializer = new JsonNetSerializer(); var provider = new UtcDateTimeProvider(); var validator = new JwtValidator(serializer, provider); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validator, urlEncoder); var json = decoder.Decode(token, secret, verify: true); return(true); } catch (TokenExpiredException) { return(false); } catch (SignatureVerificationException) { return(false); } }
public static bool ValidateToken(string token, out Employee employee) { employee = null; try { var keySec = _secret; if (string.IsNullOrWhiteSpace(AppGlobal.NexusConfig.Secret)) { keySec = AppGlobal.NexusConfig.Secret; } JWT.IJsonSerializer serializer = new JsonNetSerializer(); var provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm algorithm = new HMACSHA256Algorithm();// symmetric IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var stringToken = decoder.Decode(token, keySec, verify: true); var payLoad = JsonConvert.DeserializeObject <Dictionary <string, object> >(stringToken); var userInfoPayload = payLoad["Employee"]; employee = JsonConvert.DeserializeObject <Employee>(userInfoPayload.ToString()); return(true); } catch (TokenExpiredException) { Logger.Write("Token has expired: " + token, true); } catch (SignatureVerificationException) { Logger.Write("Token has invalid signature: " + token, true); } return(false); }
/// <summary> /// 使用自定义的密钥解密JWT文本,HS512签名 /// </summary> /// <param name="strSecretKey">密钥</param> /// <param name="strSecretMsg">需要解密的文本</param> /// <returns></returns> public static object DecodeByJwt(string strSecretKey, string strSecretMsg) { try { 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); //var json = decoder.Decode(strSecretMsg, strSecretKey, verify: true); //return json; var payload = decoder.DecodeToObject <IDictionary <string, object> >(strSecretMsg, strSecretKey, true); return(payload["Crypt"]); } catch (TokenExpiredException) { throw new Exception("Token has expired"); } catch (SignatureVerificationException) { throw new Exception("Token has invalid signature"); } }
/// <summary> /// jwt解密 /// </summary> /// <returns></returns> public static T JwtDecrypt <T>(HttpControllerContext context) { IEnumerable <string> values; context.Request.Headers.TryGetValues("token", out values); string token = values.First(); try { 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); var json = decoder.Decode(token, secret, verify: true); return(serializer.Deserialize <T>(json)); } catch (TokenExpiredException) { return(default(T)); } catch (SignatureVerificationException) { return(default(T)); } }
public string CheckToken(string Token, string KeySecret) { string[] arrToken = Token.Split("."); int lengthSalt = _appsettings.Salt.Length; string tokenSecond = arrToken[1].Substring(lengthSalt); string token = string.Format("{0}.{1}.{2}", arrToken[0], tokenSecond, arrToken[2]); string secret = KeySecret; try { 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); var json = decoder.Decode(token, secret, verify: true); return(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); return("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); return("Token has invalid signature"); } }
public static DecodedToken DecodeToken(string token) { try { 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); var json = decoder.Decode(token, _secret, verify: true); var payload = decoder.DecodeToObject <UserViewModel>(token, _secret, true); return(new DecodedToken { IsValid = true, TokenJson = payload, TokenString = json }); } catch (TokenExpiredException) { return(new DecodedToken { IsValid = false, ErrorMsg = "Token has expired" }); } catch (SignatureVerificationException) { return(new DecodedToken { IsValid = false, ErrorMsg = "Token has invalid signature" }); } }
public bool Validate(string validingJwt, string encoded64Secret) { if (string.IsNullOrEmpty(validingJwt)) { throw new MyAuthorizationException(ErrorMessage.JwtEmpty, ErrorCodeCategory.CrmAuthorization.ToString()); } var base64Decode = Base64Decode(encoded64Secret); try { 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); decoder.Decode(validingJwt, base64Decode, verify: true); } catch (TokenExpiredException) { throw new MyAuthorizationException(ErrorMessage.JwtExpired, ErrorCodeCategory.CrmAuthorization.ToString()); } catch (SignatureVerificationException) { throw new MyAuthorizationException(ErrorMessage.JwtInvalid, ErrorCodeCategory.CrmAuthorization.ToString()); } catch (System.Exception ex) { throw new MyAuthorizationException(ErrorMessage.JwtUnexpectedException, ErrorCodeCategory.CrmAuthorization.ToString(), ex.InnerException); } return(true); }
public void DecodeToObject_Should_Throw_Exception_On_Expired_Claim() { const string key = TestData.Key; const int timeDelta = -1; var algorithm = new HMACSHA256Algorithm(); var dateTimeProvider = new UtcDateTimeProvider(); var serializer = new JsonNetSerializer(); var validator = new JwtValidator(serializer, dateTimeProvider); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validator, urlEncoder); var now = dateTimeProvider.GetNow(); var exp = UnixEpoch.GetSecondsSince(now.AddHours(timeDelta)); var encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(new { exp }, key); Action decodeExpiredJwt = () => decoder.DecodeToObject <Customer>(token, key, verify: true); decodeExpiredJwt.Should() .Throw <TokenExpiredException>("because decoding an expired token should raise an exception when verified"); }
public async Task <LoginResponse> LoginUser(object parameters) { LoginResponse response; try { var result = await new HTTPHelper().SendPostRequest(APIConstants.LoginUri, parameters, false); response = JsonConvert.DeserializeObject <LoginResponse>(result) as LoginResponse; IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtDecoder decoder = new JwtDecoder(serializer, urlEncoder); var tokenResponse = JsonConvert.DeserializeObject <TokenResponse>(decoder.Decode(response.token)); tokenResponse.Token = response.token; _tokenservice.SetTokenResponse(tokenResponse); var userproducts = JsonConvert.DeserializeObject <List <ProductUserRoles> >(tokenResponse.UserRoles).Where(p => p.productId == 10); if (!userproducts.Any()) { throw new Exception($"User Don't have BDI product"); } return(response); } catch (Exception ex) { response = new LoginResponse(); response.StatusCode = ex.Message; } return(response); }
public bool validateToken(string _token) { bool verified = false; try { 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 = ConfigurationManager.AppSettings["key"].ToString(); string jsonPayload = decoder.Decode(_token, secret, verify: true); //string jsonPayload = JWT.JsonWebToken.Decode(_token, ConfigurationManager.AppSettings["key"].ToString()); verified = true; } catch (JWT.SignatureVerificationException) { verified = false; Console.WriteLine("Invalid token!"); } return(verified); }
private static string ValidateJwtToken(string token, string secret) { try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm alg = new HMACSHA256Algorithm(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, alg); var json = decoder.Decode(token); //校验通过,返回解密后的字符串 return(json); } catch (TokenExpiredException) { //表示过期 return("expired"); } catch (SignatureVerificationException) { //表示验证不通过 return("invalid"); } catch (Exception) { return("error"); } }
public Object FuncaoRetornoJWT(string token) { try { var publicKey = new X509Certificate2("my-key.p12", "password"); 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); var json = decoder.Decode(token, publicKey.ToString(), verify: true); return(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); } return(""); }
// Verifica public Object DecodingToken(string token) { try { 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); var json = decoder.Decode(token, secret, verify: false); Token tokenObj = new Token(); JObject obj = JObject.Parse(json); var aux = ((string)obj.SelectToken("exp")).Split(' '); var fecha = aux[0].Split('/'); var horas = aux[1].Split(':'); var exp = new DateTime(int.Parse(fecha[2]), int.Parse(fecha[0]), int.Parse(fecha[1]), int.Parse(horas[0]), int.Parse(horas[1]), int.Parse(horas[2])); tokenObj.IdUsuario = (int)obj.SelectToken("IdUsuario"); tokenObj.IdEscuela = (int)obj.SelectToken("IdEscuela"); return(tokenObj); } catch (TokenExpiredException) { return("Token has expired"); } catch (SignatureVerificationException) { return("Token has invalid signature"); } }
/// <summary> /// 验证token是否有效 /// </summary> /// <param name="token">token</param> public static void ValidateToken(string token) { string secret = ConfigHelper.GetConfigString("JWTSecret");; try { IJsonSerializer serializer = new JsonNetSerializer(); var provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var json = decoder.Decode(token, secret, verify: true); } catch (TokenExpiredException) { //TODO:Token验证返回信息 Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { //TODO:Token验证返回信息 Console.WriteLine("Token has invalid signature"); } }
/// <summary> /// 解密 /// </summary> public static Dictionary <string, object> Decode(string token, string key = null) { try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); var algorithm = new HMACSHA256Algorithm(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var json = decoder.Decode(token, key, verify: true); //json >> 轉dictionary Dictionary <string, object> res = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); if ((DateTime)res["timeout"] < DateTime.Now) { throw new Exception("超過期限,需重新登入"); } res.Remove("timeout"); return(res); } catch (TokenExpiredException) { throw new Exception("超過期限"); } catch (SignatureVerificationException) { throw new Exception("驗證不符,可能被竄改"); } }
public static string Jwtdecoder(string token) { try { 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); //var json = decoder.Decode(token, secret, verify: true); string json = decoder.Decode(token); return(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); } return(""); }
public HttpResponseMessage JieMi(string token) { var ajaxResult = new AjaxResult(); ajaxResult.State = "200"; ajaxResult.Message = "1获取数据成功!"; try { 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); var json = decoder.Decode(token, secret, verify: true);//token为之前生成的字符串 Console.WriteLine(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); } return(new HttpResponseMessage { Content = new StringContent(ajaxResult.SerializeJson(), System.Text.Encoding.UTF8, "application/json") }); }
// Encoding with JWT.NET is safe void DecodingWithDecoder(JwtDecoder decoder) { var decoded1 = decoder.Decode(invalidToken, secret, true); var decoded2 = decoder.Decode(invalidToken, secret, false); // Noncompliant {{Use only strong cipher algorithms when verifying the signature of this JWT.}} var decoded3 = decoder.Decode(invalidToken, secret, verify: true); var decoded4 = decoder.Decode(invalidToken, secret, verify: false); // Noncompliant var decoded5 = decoder.Decode(invalidToken, secret, verify: true); var decoded6 = decoder.Decode(invalidToken, secret, verify: false); // Noncompliant var decoded7 = decoder.Decode(invalidToken, verify: true, key: secret); var decoded8 = decoder.Decode(invalidToken, verify: false, key: secret); // Noncompliant var decoded9 = decoder.Decode(invalidToken, verify: true, key: new byte[] { 42 }); var decoded10 = decoder.Decode(invalidToken, verify: false, key: new byte[] { 42 }); // Noncompliant var decoded11 = decoder.Decode(invalidToken); // Noncompliant var decoded12 = decoder.Decode(invalidParts); // Noncompliant var decoded21 = decoder.DecodeToObject(invalidToken, secret, true); var decoded22 = decoder.DecodeToObject(invalidToken, secret, false); // Noncompliant var decoded31 = decoder.DecodeToObject <UserInfo>(invalidToken, secret, true); var decoded32 = decoder.DecodeToObject <UserInfo>(invalidToken, secret, false); // Noncompliant }
public static bool VaildateToken(string tokenkey, out TokenInfo json) { if (!string.IsNullOrEmpty(tokenkey)) { try { string token = DESEncrypt.DesDecrypt(tokenkey); byte[] key = Encoding.UTF8.GetBytes(secret); 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 result = decoder.Decode(token, key, true); json = decoder.DecodeToObject <TokenInfo>(token, key, true); if (json != null) { return(true); } } catch (Exception e) { // ignored } } json = null; return(false); }
private void webBrowser_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e) { if (e.Uri.Fragment.StartsWith("#url=") && e.Uri.Fragment.Contains("&error=1")) { this.HandleWrongUrl(e.Uri.Fragment); return; } if (!e.Uri.AbsoluteUri.StartsWith("http://localhost/#")) { return; } var parameters = new ParameterCollection(e.Uri.Fragment.Substring(1)); this.AccessToken = parameters["access_token"]; var serializer = new JsonNetSerializer(); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, urlEncoder); var payload = decoder.DecodeToObject(this.AccessToken); this.UserName = payload["username"].ToString(); this.Server = payload["ws"].ToString(); this.DialogResult = true; this.Close(); }
public static bool Decrypt <T>(string token, out T obj) where T : class { try { 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); var json = decoder.Decode(token, secret, verify: true); obj = JsonConvert.DeserializeObject <T>(json); return(true); } catch (TokenExpiredException) { obj = null; return(false); } catch (SignatureVerificationException) { obj = null; return(false); } catch (Exception) { obj = null; return(false); } }