/// <summary> /// Decode a JWT token /// </summary> /// <param name="token">JWT token encoded</param> /// <param name="secret">Specify a secret for the token</param> /// <param name="verify">Should decode verify token integrady before decrypt it</param> /// <returns>JWTDecodeResult</returns> public JwtDecodeResult Decode(string token, string secret = JwtDefaults.DEFAULT_SECRET, bool verify = true) { try { if (string.IsNullOrEmpty(token) || token.ToLower() == "null") { return(new JwtDecodeResult { AnyErrors = true, Payload = null, ErrorMessage = "Token is not valid" }); } IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtDecoder decoder = new JWT.JwtDecoder(serializer, validator, urlEncoder); var payload = decoder.DecodeToObject <IDictionary <string, object> >(token, secret, verify: true); return(new JwtDecodeResult { AnyErrors = false, Payload = payload, ErrorMessage = string.Empty }); } catch (TokenExpiredException) { return(new JwtDecodeResult { AnyErrors = true, Payload = null, ErrorMessage = JwtDefaults.TOKEN_EXPIRED }); } catch (SignatureVerificationException) { return(new JwtDecodeResult { AnyErrors = true, Payload = null, ErrorMessage = JwtDefaults.INVALID_SIGNATURE }); } }
public void BasicInspectTest() { var customData = "0123456789~!@#$%^&*()_+-=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./;'[]\\<>?\"{}|"; var payload = new Dictionary <string, object> { { "uid", "1" }, { "abc", customData } }; var tokenGenerator = new TokenGenerator(FIREBASE_SUPER_SECRET_KEY); var tokenOptions = new TokenOptions(DateTime.Now, DateTime.Now, true, true); var token = tokenGenerator.CreateToken(payload, tokenOptions); var jwtDecoder = new JWT.JwtDecoder(new JsonNetSerializer(), new JwtValidator(new JsonNetSerializer(), new UtcDateTimeProvider()), new JwtBase64UrlEncoder(), new HMACSHA256Algorithm()); var decoded = jwtDecoder.DecodeToObject(token); Assert.Multiple(() => { Assert.IsTrue(decoded.ContainsKey("v")); Assert.IsTrue(int.Parse(decoded["v"].ToString()) == 0); Assert.IsTrue(decoded["v"] is long); Assert.IsTrue(decoded.ContainsKey("d")); var c = decoded["d"]; var json = JsonConvert.SerializeObject(c); var dictionary = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); Assert.IsTrue(dictionary.ContainsKey("abc")); Assert.IsTrue(decoded.ContainsKey("exp")); Assert.IsTrue(decoded["exp"] is long); Assert.IsTrue(decoded.ContainsKey("iat")); Assert.IsTrue(decoded["iat"] is long); Assert.IsTrue(decoded.ContainsKey("nbf")); Assert.IsTrue(decoded["nbf"] is long); Assert.IsTrue(decoded.ContainsKey("admin")); Assert.IsTrue(decoded["admin"] is bool); Assert.IsTrue(decoded.ContainsKey("debug")); Assert.IsTrue(decoded["debug"] is bool); } ); }
public Payload JwtDotNet() { return(jwtDecoder.DecodeToObject <Payload>(tokenB, key, true)); }