public T DecodeToObject <T>(string token, string key, out bool isValid, out string errMsg) { isValid = false; try { var result = _jwtDecoder.DecodeToObject <T>(token, key, true); isValid = true; errMsg = "正确的token"; return(result); } catch (TokenExpiredException) { errMsg = "token过期"; return(default(T)); } catch (SignatureVerificationException) { errMsg = "签名无效"; return(default(T)); } catch (Exception) { errMsg = "token无效"; return(default(T)); } }
/// <summary> /// Decodes a token using the supplied dependencies. /// </summary> /// <param name="token">The JWT.</param> /// <returns>The payload converted to <see cref="T" />.</returns> public T Decode <T>(string token) { if (_decoder == null) { TryCreateDecoder(); } return(_verify ? _decoder.DecodeToObject <T>(token, _secret, _verify) : _decoder.DecodeToObject <T>(token)); }
public IActionResult VerifyJwt(string jwt) { try { var json = _jwtDecoder.DecodeToObject <Payload>(jwt, secret, true); return(Json(json)); } catch (Exception ex) { return(Content(ex.Message)); } }
public AuthState Login(string connectionId, string token) { var conn = Clients.FirstOrDefault(c => c.Id == connectionId); if (conn == null) { return(AuthState.InvalidConnection); } AuthState authState = AuthState.Authenticated; // Check password string requiredPassword = Settings.Default.RequiredPassword; if (!string.IsNullOrEmpty(requiredPassword)) { if (string.IsNullOrEmpty(token)) { authState |= AuthState.NoPassword; } else { try { var payload = _JwtDecoder.DecodeToObject <TokenPayload>(token); if (payload.Key != requiredPassword) { authState |= AuthState.NoPassword; } } catch (SignatureVerificationException) { authState |= AuthState.NoPassword; } } } // Check connection index against max connections if (Settings.Default.MaxSessions > 0 && Clients.IndexOf(conn) > Settings.Default.MaxSessions - 1) { authState |= AuthState.ExceedsMaxConnections; } // Check connection remote IP address against whitelist if (Settings.Default.IPWhitelist != null && Settings.Default.IPWhitelist.Count > 0 && !Settings.Default.IPWhitelist.Contains(conn.RemoteEndpoint.Address.ToString())) { authState |= AuthState.IPNotAllowed; } return(conn.AuthState = authState); }
public static JwtClaims GetJwtClaims(string jwt) { if (jwt == null) { return(new JwtClaims()); } try { return(JwtDecoder.DecodeToObject <JwtClaims>(jwt, JwtSecret, true)); } catch (TokenExpiredException) { return(new JwtClaims { Expired = true }); } catch (SignatureVerificationException) { return(new JwtClaims { Invalid = true }); } catch { return(new JwtClaims { Invalid = true }); } }
private async Task <CommandRequestStatus> Login(DeviceAuth authObject) { var loginToken = new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) .AddClaims(authObject) .WithSecret(JwtSecretKey) .Build(); logger("Logging in..."); var result = await client.PostAsync("https://api.gm.com/api/v1/oauth/token", new StringContent(loginToken)); var loginResponse = await result.Content.ReadAsStringAsync(); logger($"Response Token: {loginResponse}"); if (loginResponse.Contains("error")) { var loginErrorResponse = serializer.Deserialize <LoginError>(loginResponse); return(new CommandRequestStatus() { Successful = false, ErrorMessage = loginErrorResponse.error }); } logger(decoder.Decode(loginResponse, JwtSecretKey, verify: true)); var json = decoder.DecodeToObject <LoginReply>(loginResponse, JwtSecretKey, verify: true); AddAccessToken(json); return(new CommandRequestStatus() { Successful = true }); }
private UserException TryAuthenticate(string accessToken, out ClaimsIdentity identity) { JwtTokenPayload payload; identity = null; try { payload = _jwtDecoder.DecodeToObject <JwtTokenPayload>(accessToken, _options.JwtSecret, false); } catch (Exception ex) { _logger.Warning(ex, $"Failed to parse authentication token: {ex.Message}"); return(UserException.Create(AuthenticationError.BadToken, "Invalid authentication token.")); } if (payload.ExpiresAt < DateTime.UtcNow) { return(UserException.Create(AuthenticationError.ExpiredToken, "Authentication token is expired.")); } var parsed = Guid.TryParse(payload.Subject, out Guid userId); if (!parsed) { return(UserException.Create(AuthenticationError.BadToken, "Invalid subject.")); } var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, userId.ToString()) }; identity = new ClaimsIdentity(claims); return(null); }
public IActionResult GetByOwnerId(int id, [FromQuery] string token) { try { var json = jwtDecoder.Decode(token, secret, verify: true); var payload = jwtDecoder.DecodeToObject <IDictionary <string, int> >(token); return(new JsonResult(_dbContext.Note.Where(note => note.OwnerId == payload["id"]).ToList())); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); return(BadRequest()); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); return(BadRequest()); } catch (Exception e) { TextWriter errorWriter = Console.Error; errorWriter.WriteLine(e.Message); return(BadRequest()); } }
public FrontEnd_JWTInfo Decode_FrontEnd_Token(string token) { FrontEnd_JWTInfo retVal = null; try { retVal = _decoder.DecodeToObject <FrontEnd_JWTInfo>(token, _secret, verify: true); } catch (Exception ex) { // Log in DB Console.WriteLine("Illegal base64 exception"); } return(retVal); }
public User CreateUserFromToken(string token, out bool expired) { var userToken = _decoder.DecodeToObject <UserToken>(token, _tokenSecret, false); expired = userToken.exp < DateTime.Now; var user = MapTokenToUser(userToken); return(user); }
public T Read <T>(string token, bool verify) { try { return(_decoder.DecodeToObject <T>(token, _secret, verify: verify)); } catch (Exception ex) { _logger.LogError(ex, token); return(default(T)); } }
/// <summary> /// use <see cref="IJwtDecoder.DecodeToObject(string, byte[], bool)"/> and verify is always on /// </summary> /// <param name="jwtDecoder"></param> /// <param name="token">The JWT.</param> /// <param name="key">The key that was used to sign the JWT.</param> /// <param name="result">An object representing the payload.</param> /// <returns>true if s was converted successfully; otherwise, false.</returns> public static bool TryDecodeToObject(this IJwtDecoder jwtDecoder, string token, byte[] key, out IDictionary <string, object> result) { try { result = jwtDecoder.DecodeToObject(token, key, true); return(true); } catch { result = null; return(false); } }
/// <summary> /// use <see cref="IJwtDecoder.DecodeToObject{T}(string, byte[], bool)"/> and verify is always on /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jwtDecoder"></param> /// <param name="token">The JWT.</param> /// <param name="key">The key that was used to sign the JWT.</param> /// <param name="result">An object representing the payload.</param> /// <returns>true if s was converted successfully; otherwise, false.</returns> public static bool TryDecodeToObject <T>(this IJwtDecoder jwtDecoder, string token, byte[] key, out T result) { try { result = jwtDecoder.DecodeToObject <T>(token, key, true); return(true); } catch { result = default(T); return(false); } }
public T DecodeToken <T>(string token) where T : class { try { if (string.IsNullOrWhiteSpace(token)) { return(null); } return(decoder.DecodeToObject <T>(token, SecretKey, true)); } catch (TokenExpiredException) { return(null); } catch (SignatureVerificationException) { return(null); } catch (Exception) { var data = decoder.DecodeToObject <DataModel>(token, SecretKey, true).Data; return(JsonConvert.DeserializeObject <T>(JsonConvert.SerializeObject(data))); } }
public static IDictionary <string, object> GetPrincipal(string token) { try { IDictionary <string, object> json = decoder.DecodeToObject(token, Secret, verify: true); return(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); } return(null); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var header = bindingContext.HttpContext.Request.Headers["Authorization"]; if (header.Count != 1) { bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, $"Found {header.Count} authorization headers, expected 1."); return(Task.CompletedTask); } var token = header[0].StartsWith("Bearer ") ? header[0].Substring("Bearer ".Length) : header[0]; var result = decoder.DecodeToObject <TokenJwt>(token, _secret, false); bindingContext.Result = ModelBindingResult.Success(result); return(Task.CompletedTask); }
public Payload Parse(string token) { return(_decoder.DecodeToObject <Payload>(token, SECRET, verify: true)); }
/// <summary> /// Decodes a token using the supplied dependencies. /// </summary> /// <param name="token">The JWT</param> /// <returns>The payload converted to <see cref="T" /></returns> public T Decode <T>(string token) { EnsureCanDecode(); return(_verify ? _decoder.DecodeToObject <T>(token, _secrets, _verify) : _decoder.DecodeToObject <T>(token)); }
public UsuarioLogin RecuperarInformacionDeUsuario(string token) { return(decoder.DecodeToObject <UsuarioLogin>(token, SECRET_KEY, verify: true)); }
/// <summary> /// Given a JWT, decodes it and return the payload as an object. /// </summary> /// <typeparam name="T">The type to return</typeparam> /// <param name="decoder">The decoder instance</param> /// <param name="token">The JWT</param> /// <param name="keys">The keys provided which one of them was used to sign the JWT</param> /// <param name="verify">Whether to verify the signature (default is true)</param> /// <returns>An object representing the payload</returns> public static T DecodeToObject <T>(this IJwtDecoder decoder, string token, string[] keys, bool verify) => decoder.DecodeToObject <T>(token, GetBytes(keys), verify);
public static IDictionary <string, object> DecodeToObject(this IJwtDecoder decoder, string token, byte[][] keys, bool verify) => decoder.DecodeToObject <Dictionary <string, object> >(token, keys, verify);
public static IDictionary <string, object> DecodeToObject(this IJwtDecoder decoder, string token, string[] keys, bool verify) => decoder.DecodeToObject(token, GetBytes(keys), verify);
/// <summary> /// Given a JWT, decodes it and return the payload as a dictionary. /// </summary> /// <param name="decoder">The decoder instance</param> /// <param name="token">The JWT</param> /// <returns>An object representing the payload</returns> public static IDictionary <string, object> DecodeToObject(this IJwtDecoder decoder, string token) => decoder.DecodeToObject <Dictionary <string, object> >(token);
public IDictionary <string, object> GetDecodedAccessToken(string token) { return(_decoder.DecodeToObject(token, _jwtSettings.SecretKey, true)); }
/// <summary> /// Given a JWT, decodes it and return the payload as an object. /// </summary> /// <typeparam name="T">The type to return</typeparam> /// <param name="decoder">The decoder instance</param> /// <param name="token">The JWT</param> /// <param name="keys">The keys provided which one of them was used to sign the JWT</param> /// <param name="verify">Whether to verify the signature (default is true)</param> /// <returns>An object representing the payload</returns> public static T DecodeToObject <T>(this IJwtDecoder decoder, string token, byte[][] keys, bool verify) => decoder.DecodeToObject <T>(new JwtParts(token), keys, verify);
/// <summary> /// Given a JWT, decodes it and return the payload as an object. /// </summary> /// <typeparam name="T">The type to return</typeparam> /// <param name="decoder">The decoder instance</param> /// <param name="token">The JWT</param> /// <returns>An object representing the payload</returns> public static T DecodeToObject <T>(this IJwtDecoder decoder, string token) => decoder.DecodeToObject <T>(new JwtParts(token));