コード例 #1
0
        /// <summary>
        /// Decode object with secret
        /// </summary>
        /// <param name="secretToken"></param>
        /// <param name="token"></param>
        /// <returns>Complete object with expire date</returns>
        public OutputDto <string> Decode(string secretToken, string token)
        {
            try
            {
                //Decode JWT token
                string decodedToken = _jwtDecoder.Decode(token, secretToken, verify: true);

                //Decode Token
                DecodeToken(decodedToken, out string content, out DateTime? parsedDateTime);

                if (parsedDateTime.HasValue)
                {
                    //Return converted Object
                    return(new OutputDto <string>(content, HttpStatusCode.OK, ToUtc(parsedDateTime.Value)));
                }
                else
                {
                    return(new OutputDto <string>(content));
                }
            }
            catch (TokenExpiredException ex)
            {
                return(new OutputDto <string>(HttpStatusCode.Unauthorized, "Token has expired", ex.ToString()));
            }
            catch (SignatureVerificationException ex)
            {
                return(new OutputDto <string>(HttpStatusCode.Unauthorized, "Token has invalid signature", ex.ToString()));
            }
        }
コード例 #2
0
ファイル: JwtBuilder.cs プロジェクト: CodingMate/jwt
        /// <summary>
        /// Decodes a token using the supplied dependencies.
        /// </summary>
        /// <param name="token">The JWT.</param>
        /// <returns>The JSON payload</returns>
        public string Decode(string token)
        {
            if (_decoder == null)
            {
                TryCreateDecoder();
            }

            return(_verify ? _decoder.Decode(token, _secrets, _verify) : _decoder.Decode(token));
        }
コード例 #3
0
        public async Task <string> GetAzureUserAsync(string code)
        {
            using var client = new HttpClient
                  {
                      BaseAddress = new Uri($"{AzureAdUrl}")
                  };
            var data = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("grant_type", "authorization_code"),
                new KeyValuePair <string, string>("code", code),
                new KeyValuePair <string, string>("client_id", _config["AzureAD:ClientId"]),
                new KeyValuePair <string, string>("client_secret", _config["AzureAD:ClientSecret"]),
                new KeyValuePair <string, string>("redirect_uri", _config["AzureAD:RedirectUri"]),
                new KeyValuePair <string, string>("scope", "openid%20profile%20email")
            });
            var result = await client.PostAsync($"/{ _config["AzureAD:TenantId"]}/oauth2/token", data);

            var content = await result.Content.ReadAsStringAsync();

            var json    = JObject.Parse(content);
            var idToken = json.Value <string>("id_token");
            var jwt     = _jwtDecoder.Decode(idToken);

            return(jwt.Claims.First(x => x.Type == "email").Value);
        }
コード例 #4
0
        public static bool IsTokenValid(string token, string jwtSecretKey, bool checkExpiration = true)
        {
            var result = false;

            _decoder = new JwtDecoder(_serializer, _validator, _urlEncoder);
            var payloadJson = _decoder.Decode(token, jwtSecretKey, checkExpiration);
            var payloadData = JsonHelper.Deserialize <Dictionary <string, object> >(payloadJson);

            object expiryTime;

            if (payloadData != null)
            {
                if (checkExpiration)
                {
                    if (payloadData.TryGetValue("exp", out expiryTime))
                    {
                        var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                        var validTo   = unixEpoch.AddSeconds(long.Parse(expiryTime.ToString()));

                        if (DateTime.Compare(validTo, DateTime.UtcNow) <= 0)
                        {
                            result = false;
                        }
                        else
                        {
                            result = true;
                        }
                    }
                }
            }

            return(result);
        }
コード例 #5
0
        public T Decode <T>(string jwt)
        {
            var jDict = JsonConvert.DeserializeObject <JObject>(decoder.Decode(jwt));
            var json  = (jDict.GetValue(payloadKey) as JValue).Value <string>();

            return(JsonConvert.DeserializeObject <T>(json, jsonSerializerSettings));
        }
コード例 #6
0
        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());
            }
        }
コード例 #7
0
        public string Decode(string token, string key, out bool isValid, out string errMsg)
        {
            isValid = false;
            var result = string.Empty;

            try
            {
                result  = _jwtDecoder.Decode(token, key, true);
                isValid = true;
                errMsg  = "正确的token";
                return(result);
            }
            catch (TokenExpiredException)
            {
                errMsg = "token过期";
                return(result);
            }
            catch (SignatureVerificationException)
            {
                errMsg = "签名无效";
                return(result);
            }
            catch (Exception)
            {
                errMsg = "token无效";
                return(result);
            }
        }
コード例 #8
0
ファイル: OnStarClient.cs プロジェクト: BrendanGrant/NOnStar
        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
            });
        }
コード例 #9
0
        public static T Decode <T>(string jwt)
        {
            var jDictionary = JsonConvert.DeserializeObject <JObject>(decoder.Decode(jwt));
            var json        = jDictionary.Property(key).Value.ToObject <string>();

            return(JsonConvert.DeserializeObject <T>(json, serializerSettings));
        }
コード例 #10
0
        public AuthInfo DecodeAndGetUserFromToken(string token)
        {
            try
            {
                var rawJsonToken  = _jwtDecoder.Decode(token, _jwtSecretToken, true);
                var parsedRawJson = JsonConvert.DeserializeObject <Dictionary <string, string> >(rawJsonToken);

                var isValidToken = true;
                if (!parsedRawJson.ContainsKey(Expiration))
                {
                    return(new AuthInfo(isValidToken)
                    {
                        UserName = parsedRawJson["UserName"],
                    });
                }

                var expirationDate = new DateTime(long.Parse(parsedRawJson[Expiration]));

                isValidToken = expirationDate - DateTime.UtcNow > TimeSpan.Zero;

                return(new AuthInfo(isValidToken, isValidToken ? (AuthFailure?)null : AuthFailure.Expired)
                {
                    UserName = parsedRawJson["UserName"],
                });
            }
            catch (Exception)
            {
                return(new AuthInfo(false, AuthFailure.InvalidToken));
            }
        }
コード例 #11
0
ファイル: JwtBuilder.cs プロジェクト: light12138/Jwt
 public string CheckToken(string token)
 {
     if (_decoder == null)
     {
         TryCreateDecoder();
     }
     EnsureCanBuild();
     return(_decoder.Decode(token, _secret, _verify));
 }
コード例 #12
0
ファイル: JWTService.cs プロジェクト: heineking/Daily-Tracker
        public Token DecodeToken(string jwt)
        {
            var decoded = _decoder.Decode(jwt, _key, verify: true);
            var token   = JsonConvert.DeserializeObject <Token>(decoded);

            if (token.Exp < DateTime.Now)
            {
                return(null);
            }
            return(token);
        }
コード例 #13
0
ファイル: JwtImpl.cs プロジェクト: gitWanggg/XMService
 public TokenModel Decoding(string base64Token)
 {
     try {
         var json = decoder.Decode(base64Token, ISec.SecretCurrent, verify: true);
         return(Newtonsoft.Json.JsonConvert.DeserializeObject <TokenModel>(json));
     }
     catch (TokenExpiredException) {
         return(null);
     }
     catch (SignatureVerificationException) {
         return(null);
     }
 }
コード例 #14
0
 /// <summary>
 /// verify token
 /// </summary>
 /// <param name="jwt"></param>
 /// <returns></returns>
 public IActionResult TokenVerify(string jwt)
 {
     try
     {
         //decode
         var json = _jwtDecoder.Decode(jwt, secret, true);
         return(Content(json));
     }
     catch (Exception ex)
     {
         return(Content(ex.Message));
     }
 }
コード例 #15
0
ファイル: JWTTools.cs プロジェクト: A0000000000/Shop
 public static Tuple <string, DateTime> Decode(string token, bool isAdmin = false)
 {
     try
     {
         string json = decoder.Decode(token, Secret + (isAdmin ? " admin" : ""), true);
         Dictionary <string, object> dic = JsonSerializer.Deserialize <Dictionary <string, object> >(json);
         return(new Tuple <string, DateTime>(dic["username"]?.ToString(), DateTime.Parse(dic["datetime"]?.ToString() ?? string.Empty)));
     }
     catch (Exception e)
     {
         return(null);
     }
 }
コード例 #16
0
 /// <summary>
 /// use <see cref="IJwtDecoder.Decode(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">A string containing the JSON payload.</param>
 /// <returns>true if s was converted successfully; otherwise, false.</returns>
 public static bool TryDecode(this IJwtDecoder jwtDecoder, string token, byte[] key, out string result)
 {
     try
     {
         result = jwtDecoder.Decode(token, key, true);
         return(true);
     }
     catch
     {
         result = null;
         return(false);
     }
 }
コード例 #17
0
        public TokenModel ValidateToken(string token)
        {
            try
            {
                var tokenJsonData = _decoder.Decode(token, _secretKeys.Value.StreamTokenSecretKey, verify: true);
                var tokenModel    = JsonConvert.DeserializeObject <TokenModel>(tokenJsonData);

                return(tokenModel);
            }
            catch (Exception ex)
            {
                _logger.LogError("Token validation filed", ex);
                throw;
            }
        }
コード例 #18
0
ファイル: TokenMaker.cs プロジェクト: Ruannilton/Half-Pugg
 public string ValidateToken(string token)
 {
     try
     {
         var data = decoder.Decode(token, secret, verify: true);
         return(data);
     } catch (TokenExpiredException)
     {
         Console.WriteLine("Token expirado");
     }
     catch (SignatureVerificationException)
     {
         Console.WriteLine("Token inválido");
     }
     return(null);
 }
コード例 #19
0
 public string DecodeToken(string token)
 {
     try
     {
         if (string.IsNullOrWhiteSpace(token) || token == "null")
         {
             return(null);
         }
         return(decoder.Decode(token, SecretKey, true));
     }
     catch (TokenExpiredException)
     {
         return(null);
     }
     catch (SignatureVerificationException)
     {
         return(null);
     }
 }
コード例 #20
0
ファイル: JWT_Provider.cs プロジェクト: gauravi-lad/Spice
        public bool Verify_Token(string token)
        {
            bool flag = false;

            try
            {
                var json = _decoder.Decode(token, _secret, verify: true);

                Console.WriteLine(json);

                flag = true;
            }
            catch (Exception ex)
            {
                // Log in DB
                Console.WriteLine("Illegal base64 exception");
            }

            return(flag);
        }
コード例 #21
0
        public LoggedInPerson GetLoggedInPerson()
        {
            var person = new LoggedInPerson();

            try
            {
                var token = _httpContextAccessor.HttpContext.Request.Headers["jwtCookie"];

                if (!string.IsNullOrEmpty(token))
                {
                    person = _decoder.Decode(token);
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Exception thrown in GroupAuthorisation, {ex.Message}");
            }

            return(person);
        }
コード例 #22
0
        /// <inheritdoc/>
        public async Task <T> DecodeAsync <T>(string token, CancellationToken ct)
            where T : BaseTokenModel
        {
            Ensure.ArgumentNotNull(ct, nameof(ct));

            ct.ThrowIfCancellationRequested();

            try
            {
                var decoded = decoder.Decode(token, configuration.Options.AuthOptions.JwtOptions.SecretKey, true);
                var result  = serializer.Deserialize <T>(decoded);

                await Task.CompletedTask;

                return(result);
            }
            catch (Exception e)
            {
                logger.LogError(e, e.Message);
                throw new AmiException("The provided token could not be decoded.");
            }
        }
コード例 #23
0
        /// <summary>
        /// Decodes a token using the supplied dependencies.
        /// </summary>
        /// <param name="token">The JWT</param>
        /// <returns>The JSON payload</returns>
        public string Decode(string token)
        {
            EnsureCanDecode();

            return(_verify ? _decoder.Decode(token, _secrets, _verify) : _decoder.Decode(token));
        }
コード例 #24
0
 /// <summary>
 /// Given a JWT, decodes it and return the payload.
 /// </summary>
 /// <param name="decoder">The decoder instance</param>
 /// <param name="token">The JWT</param>
 /// <returns>A string containing the JSON payload</returns>
 /// <exception cref="ArgumentException" />
 /// <exception cref="ArgumentOutOfRangeException" />
 /// <exception cref="InvalidTokenPartsException" />
 public static string Decode(this IJwtDecoder decoder, string token) =>
 decoder.Decode(new JwtParts(token));
コード例 #25
0
 /// <summary>
 /// Given a JWT, decodes it and return the payload.
 /// </summary>
 /// <param name="decoder">The decoder instance</param>
 /// <param name="jwt">The JWT</param>
 /// <returns>A string containing the JSON payload</returns>
 public static string Decode(this IJwtDecoder decoder, JwtParts jwt) =>
 decoder.Decode(jwt, (byte[])null, verify: false);
コード例 #26
0
 /// <summary>
 /// Given a JWT, decodes it and return the payload.
 /// </summary>
 /// <param name="decoder">The decoder instance</param>
 /// <param name="token">The JWT</param>
 /// <param name="keys">The keys that were used to sign the JWT</param>
 /// <param name="verify">Whether to verify the signature (default is true)</param>
 /// <returns>A string containing the JSON payload</returns>
 /// <exception cref="ArgumentException" />
 /// <exception cref="ArgumentOutOfRangeException" />
 /// <exception cref="InvalidTokenPartsException" />
 public static string Decode(this IJwtDecoder decoder, string token, byte[][] keys, bool verify) =>
 decoder.Decode(new JwtParts(token), keys, verify);
コード例 #27
0
        public LoginToken DecodeToken(string jwt)
        {
            var decoded = _decoder.Decode(jwt, _key, verify: true);

            return(JsonConvert.DeserializeObject <LoginToken>(decoded));
        }
コード例 #28
0
 public JObject Decode(string jwt)
 {
     return(JsonConvert.DeserializeObject <JObject>(decoder.Decode(jwt)));
 }
コード例 #29
0
 /// <summary>
 /// Given a JWT, decodes it and return the payload as an dictionary.
 /// </summary>
 /// <param name="decoder">The decoder instance</param>
 /// <param name="token">The JWT</param>
 /// <param name="keys">The key 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>
 /// <exception cref="ArgumentException" />
 /// <exception cref="ArgumentOutOfRangeException" />
 public static string Decode(this IJwtDecoder decoder, string token, string[] keys, bool verify) =>
 decoder.Decode(token, GetBytes(keys), verify);