Пример #1
0
    public TokenDecoded(string token, bool verify)
    {
        if (verify)
        {
            var json = JwtBuilder.Create()
                       .WithAlgorithm(new HMACSHA256Algorithm()) // symmetric
                       .WithSecret(GlobalVariables.TokenDecodeString)
                       .MustVerifySignature()
                       .Decode(token);

            TokenDecoded aux = JsonUtility.FromJson <TokenDecoded>(json);
            this.userTag = aux.userTag;
            this.iat     = aux.iat;
            this.exp     = aux.exp;
        }
        else
        {
            var json = JwtBuilder.Create()
                       .WithAlgorithm(new HMACSHA256Algorithm()) // symmetric
                       .WithSecret(GlobalVariables.TokenDecodeString)
                       .Decode(token);

            TokenDecoded aux = JsonUtility.FromJson <TokenDecoded>(json);
            this.userTag = aux.userTag;
            this.iat     = aux.iat;
            this.exp     = aux.exp;
        }
    }
        public static (bool, IDictionary <string, object>) ValidatePublicJWTToken(string jwtToken, IDictionary <string, string> claims)
        {
            try
            {
                var validationParameters = ValidationParameters.None;
                validationParameters.ValidateExpirationTime = true;
                var data = JwtBuilder.Create()
                           .WithDateTimeProvider(new UtcDateTimeProvider())
                           .WithValidationParameters(validationParameters)
                           .WithSerializer(new JsonNetSerializer())
                           .WithUrlEncoder(new JwtBase64UrlEncoder())
                           .Decode <IDictionary <string, object> >(jwtToken);
                foreach (var claim in claims)
                {
                    var value = data.GetOrDefault(claim.Key, "").ToString();
                    if (value != claim.Value)
                    {
                        return(false, null);
                    }
                }

                return(true, data);
            }
            catch (TokenExpiredException)
            {
                Logger.Log?.LogError($"Token {jwtToken} is expired");
                return(false, null);
            }
            catch (Exception ex)
            {
                Logger.Log?.LogError($"Parsing token {jwtToken} error {ex.Message}");
                return(false, null);
            }
        }
Пример #3
0
 private void DecodeToken(string token)
 {
     try
     {
         var payload = JwtBuilder.Create()
                       .WithAlgorithm(new HMACSHA256Algorithm()) // symmetric
                       .WithSecret(Secret)
                       .MustVerifySignature()
                       .Decode <IDictionary <string, object> >(token);
         UserId          = payload["userId"].ToString();
         TokenValidState = TokenValidState.Valid;
     }
     catch (TokenExpiredException)
     {
         //表示过期
         TokenValidState = TokenValidState.Expired;
     }
     catch (SignatureVerificationException)
     {
         //表示验证不通过
         TokenValidState = TokenValidState.Invalid;
     }
     catch (Exception e)
     {
         TokenValidState = TokenValidState.Error;
     }
 }
Пример #4
0
        public override ApiHandlerOutput Process(ApiInputHandler input)
        {
            string bearer = input.Context.Request.Headers["ZestyApiBearer"];

            if (String.IsNullOrWhiteSpace(bearer))
            {
                ThrowApplicationError("Bearer non found");
            }

            string secret = Business.User.GetSecret(bearer);

            string token = JwtBuilder.Create()
                           .WithAlgorithm(new HMACSHA256Algorithm())
                           .WithSecret(secret)
                           .AddClaim("exp", DateTimeOffset.UtcNow.AddHours(12).ToUnixTimeSeconds())
                           .AddClaim("user", Context.Current.User)
                           .Encode();

            logger.Debug($"token generated: {token}");

            Business.User.SaveBearer(Context.Current.User.Id, token);

            RefreshResponse response = new RefreshResponse()
            {
                Bearer = token
            };

            return(GetOutput());
        }
Пример #5
0
        /// <summary>
        /// Builds a JSON Web Token value.
        /// </summary>
        /// <returns></returns>
        public static string GetJwtString()
        {
            string tokenString = null;

            using (RockContext rockContext = new RockContext())
            {
                var settings = GetSettings(rockContext);
                if (settings != null)
                {
                    var zoomApiKey    = GetSettingValue(settings, "rocks.kfs.ZoomApiKey", true);
                    var zoomApiSecret = GetSettingValue(settings, "rocks.kfs.ZoomApiSecret", true);
                    if (!String.IsNullOrWhiteSpace(zoomApiKey) && !String.IsNullOrWhiteSpace(zoomApiKey))
                    {
                        tokenString = JwtBuilder.Create()
                                      .WithAlgorithm(new HMACSHA256Algorithm())
                                      .WithSecret(zoomApiSecret)
                                      .AddClaim("aud", null)
                                      .AddClaim("iss", zoomApiKey)
                                      .AddClaim("exp", DateTimeOffset.UtcNow.AddHours(1).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds) // Replace .Subtract() with  .ToUnixTimeSeconds() once assembly is moved to .NET 4.6+
                                      .AddClaim("iat", DateTimeOffset.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds)             // Replace .Subtract() with  .ToUnixTimeSeconds() once assembly is moved to .NET 4.6+
                                      .Encode();
                    }
                }
            }
            return(tokenString);
        }
Пример #6
0
 /// <summary>
 /// This constructor initializes a new RequestValidator instance.
 /// </summary>
 ///
 /// <param name="secret">signing key. Can be retrieved from https://dashboard.messagebird.com/developers/settings. This is NOT your API key.</param>
 /// <param name="skipURLValidation">whether url_hash claim validation should be skipped. Note that when true, no query parameters should be trusted.</param>
 /// <see href="https://developers.messagebird.com/docs/verify-http-requests" />
 public RequestValidator(string secret, bool skipURLValidation = false)
 {
     _jwtBuilder = JwtBuilder.Create()
                   .WithAlgorithmFactory(new JWT.Algorithms.HMACSHAAlgorithmFactory())
                   .WithSecret(secret)
                   .MustVerifySignature();
     _skipURLValidation = skipURLValidation;
 }
Пример #7
0
 public Jwt()
 {
     Builder = JwtBuilder.Create()
               .WithAlgorithm(new HMACSHA256Algorithm())
               .WithSerializer(new JsonNetSerializer())
               .WithUrlEncoder(new JwtBase64UrlEncoder())
               .WithSecret(Secret);
 }
Пример #8
0
        private void LoadUser(HttpContext context)
        {
            Context.Current.Reset();

            Context.Current.User = context.Session.Get <Entities.User>(Keys.SessionUser);

            if (Context.Current.User != null)
            {
                return;
            }

            string bearer = context.Request.Headers["ZestyApiBearer"];

            if (String.IsNullOrWhiteSpace(bearer))
            {
                return;
            }

            logger.Info($"Bearer received: {bearer}");

            string secret = Business.User.GetSecret(bearer);

            if (String.IsNullOrWhiteSpace(secret))
            {
                throw new SecurityException("Invalid token");
            }

            var json = JwtBuilder.Create()
                       .WithAlgorithm(new HMACSHA256Algorithm())
                       .WithSecret(secret)
                       .MustVerifySignature()
                       .Decode(bearer);

            logger.Debug($"Json from bearer: {json}");

            Bearer b = JsonHelper.Deserialize <Bearer>(json);

            if (b == null || b.User == null)
            {
                return;
            }

            DateTime expiration = DateTimeHelper.GetFromUnixTimestamp(b.Exp);

            if (expiration < DateTime.Now && context.Request.Path != refreshResource)
            {
                throw new ApiTokenExpiredException("Token expired");
            }

            if (b.User.DomainId != Guid.Empty)
            {
                List <Domain> domains = Business.User.GetDomains(b.User.Username);

                b.User.Domain = domains.Where(x => x.Id == b.User.DomainId).FirstOrDefault();
            }

            Context.Current.User = b.User;
        }
Пример #9
0
        public void Decode_Should_Return_Token()
        {
            var token = JwtBuilder.Create()
                        .WithAlgorithm(TestData.RS256Algorithm)
                        .Decode(TestData.Token);

            token.Should()
            .NotBeNullOrEmpty("because the decoded token contains values and they should have been decoded");
        }
Пример #10
0
        public void DecodeHeader_Should_Return_Header()
        {
            var header = JwtBuilder.Create()
                         .WithAlgorithm(TestData.RS256Algorithm)
                         .DecodeHeader(TestData.TokenByAsymmetricAlgorithm);

            header.Should()
            .NotBeNullOrEmpty("because decoding header should be possible without validator or algorithm");
        }
Пример #11
0
        public void Encode_Without_Dependencies_Should_Throw_Exception()
        {
            Action action = () =>
                            JwtBuilder.Create()
                            .Encode();

            action.Should()
            .Throw <InvalidOperationException>("because a JWT can't be built without dependencies");
        }
Пример #12
0
        public void Decode_Without_Validator_Should_Return_Token()
        {
            var token = JwtBuilder.Create()
                        .WithAlgorithm(TestData.RS256Algorithm)
                        .WithValidator(null)
                        .Decode(TestData.Token);

            token.Should()
            .NotBeNullOrEmpty("because a JWT should not necessary have validator to be decoded");
        }
Пример #13
0
        public void Decode_Without_VerifySignature_Should_Return_Token()
        {
            var token = JwtBuilder.Create()
                        .WithAlgorithm(TestData.RS256Algorithm)
                        .DoNotVerifySignature()
                        .Decode(TestData.Token);

            token.Should()
            .NotBeNullOrEmpty("because token should have been decoded without errors");
        }
Пример #14
0
        public void Decode_Without_Serializer_Should_Throw_Exception()
        {
            Action action =
                () => JwtBuilder.Create()
                .WithSerializer(null)
                .Decode(TestData.Token);

            action.Should()
            .Throw <InvalidOperationException>("because token can't be decoded without valid serializer");
        }
Пример #15
0
        public void Decode_Without_Token_Should_Throw_Exception()
        {
            Action action =
                () => JwtBuilder.Create()
                .WithAlgorithm(TestData.RS256Algorithm)
                .Decode(null);

            action.Should()
            .Throw <ArgumentException>("because null is not valid value for token");
        }
Пример #16
0
        public void Decode_With_VerifySignature_Should_Return_Token_When_Algorithm_Is_Asymmetric()
        {
            var token = JwtBuilder.Create()
                        .WithAlgorithm(TestData.RS256Algorithm)
                        .MustVerifySignature()
                        .Decode(TestData.TokenByAsymmetricAlgorithm);

            token.Should()
            .NotBeNullOrEmpty("because the signature must have been verified successfully and the JWT correctly decoded");
        }
Пример #17
0
        public void NoneAlgorithmFluentApi()
        {
            String jwtString = JwtBuilder.Create().WithAlgorithm(NoneAlgorithmType.None)
                               .Encode(Payload);

            Payload payload = JwtBuilder.Create().WithAlgorithm(NoneAlgorithmType.None)
                              .Decode <Payload>(jwtString);

            Assert.IsTrue(payload != null && Payload.Username == payload.Username);
        }
        private async Task <KeycloakUser> GetKeycloakUser(string username, string password, string totp)
        {
            var httpClient = GetHttpClient();
            var keyValues  = new List <KeyValuePair <string, string> >();

            keyValues.Add(new KeyValuePair <string, string>("username", username));
            keyValues.Add(new KeyValuePair <string, string>("password", password));
            keyValues.Add(new KeyValuePair <string, string>("grant_type", "password"));
            keyValues.Add(new KeyValuePair <string, string>("client_id", Resource));
            if (!String.IsNullOrWhiteSpace(ClientSecret))
            {
                keyValues.Add(new KeyValuePair <string, string>("client_secret", ClientSecret));
            }

            if (!String.IsNullOrWhiteSpace(totp))
            {
                keyValues.Add(new KeyValuePair <string, string>("totp", totp));
            }

            var content  = new FormUrlEncodedContent(keyValues);
            var response = await httpClient.PostAsync(TokenURI, content).ConfigureAwait(false);

            var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

            var parsed = await JsonSerializer.DeserializeAsync <KeycloakTokenResponse>(responseStream).ConfigureAwait(false);

            if (parsed == null)
            {
                return(null);
            }
            try
            {
                var           jwtToken = JwtBuilder.Create().Decode <IDictionary <string, object> >(parsed.access_token);
                List <string> perms    = new List <string>();
                try
                {
                    var resourceAccess = (JObject)jwtToken["resource_access"];
                    perms = ((JArray)(((JObject)resourceAccess[Resource])["roles"])).ToObject <List <string> >();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"Could not parse permissions for resource {Resource}");
                }

                return(new KeycloakUser {
                    Username = username, Permissions = perms
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error parsing jwt token");
            }

            return(null);
        }
Пример #19
0
        public void Decode_Without_TimeProvider_Should_Throw_Exception()
        {
            Action action =
                () => JwtBuilder.Create()
                .WithAlgorithm(TestData.RS256Algorithm)
                .WithDateTimeProvider(null)
                .Decode(TestData.Token);

            action.Should()
            .Throw <InvalidOperationException>("because token can't be decoded without valid DateTimeProvider");
        }
Пример #20
0
        public void Decode_With_VerifySignature_And_Without_AlgorithmFactory_Should_Throw_Exception()
        {
            Action action =
                () => JwtBuilder.Create()
                .WithAlgorithmFactory(null)
                .MustVerifySignature()
                .Decode(TestData.Token);

            action.Should()
            .Throw <InvalidOperationException>("because token can't be decoded without valid algorithm or algorithm factory");
        }
Пример #21
0
        private void CreateToken()
        {
            var token = JwtBuilder.Create()
                        .WithAlgorithm(new HMACSHA256Algorithm()) // symmetric
                        .WithSecret(Secret)
                        .AddClaim("exp", Expire)
                        .AddClaim("userId", UserId)
                        .Encode();

            Token = token;
        }
Пример #22
0
        public void Decode_Without_VerifySignature_And_Without_Algorithm_Should_Return_Token()
        {
            var token = JwtBuilder.Create()
                        .WithAlgorithm(null)
                        .WithValidator(null)
                        .DoNotVerifySignature()
                        .Decode(TestData.Token);

            token.Should()
            .NotBeNullOrEmpty("because the decoding process without validating signature must be successful without validator and algorithm");
        }
Пример #23
0
        public void Decode_ToObject_With_Multiple_Secrets_Should_Return_Object()
        {
            var token = JwtBuilder.Create()
                        .WithAlgorithm(TestData.HMACSHA256Algorithm)
                        .WithSecret(TestData.Secrets)
                        .MustVerifySignature()
                        .Decode <Customer>(TestData.Token);

            token.FirstName.Should().Be("Jesus");
            token.Age.Should().Be(33);
        }
Пример #24
0
        public void Decode_With_VerifySignature_With_Multiple_Secrets_Should_Return_Token()
        {
            var token = JwtBuilder.Create()
                        .WithAlgorithm(TestData.HMACSHA256Algorithm)
                        .WithSecret(TestData.Secrets)
                        .MustVerifySignature()
                        .Decode(TestData.Token);

            token.Should()
            .NotBeNullOrEmpty("because one of the provided signatures must have been verified successfully and the JWT correctly decoded");
        }
Пример #25
0
        public void HS512AlgorithmFluentApi()
        {
            String jwtString = JwtBuilder.Create().WithAlgorithm(SymmetricAlgorithmType.HS512)
                               .WithKey(KeySet.Key)
                               .Encode(Payload);

            Payload payload = JwtBuilder.Create().WithAlgorithm(SymmetricAlgorithmType.HS512)
                              .WithKey(KeySet.Key)
                              .Decode <Payload>(jwtString);

            Assert.IsTrue(payload != null && Payload.Username == payload.Username);
        }
 public static IDictionary <string, object> DecodeJWTToken(string jwtToken)
 {
     try
     {
         return(JwtBuilder.Create()
                .Decode <IDictionary <string, object> >(jwtToken));
     }
     catch (Exception)
     {
         return(new Dictionary <string, object>());
     }
 }
Пример #27
0
        public void ES512AlgorithmFluentApi()
        {
            String jwtString = JwtBuilder.Create().WithAlgorithm(AsymmetricAlgorithmType.ES512)
                               .WithKey((PemPrivateKey)KeySet.EcdsaPrivateKey)
                               .Encode(Payload);

            Payload payload = JwtBuilder.Create().WithAlgorithm(AsymmetricAlgorithmType.ES512)
                              .WithKey((PemPublicKey)KeySet.EcdsaPublicKey)
                              .Decode <Payload>(jwtString);

            Assert.IsTrue(payload != null && Payload.Username == payload.Username);
        }
Пример #28
0
        public void Decode_With_Serializer_Should_Return_Token()
        {
            var serializer = new JsonNetSerializer();

            var token = JwtBuilder.Create()
                        .WithAlgorithm(TestData.RS256Algorithm)
                        .WithSerializer(serializer)
                        .Decode(TestData.Token);

            token.Should()
            .NotBeNullOrEmpty("because token should be correctly decoded and its data extracted");
        }
Пример #29
0
        public void Decode_With_UrlEncoder_Should_Return_Token()
        {
            var urlEncoder = new JwtBase64UrlEncoder();

            var token = JwtBuilder.Create()
                        .WithAlgorithm(TestData.RS256Algorithm)
                        .WithUrlEncoder(urlEncoder)
                        .Decode(TestData.Token);

            token.Should()
            .NotBeNullOrEmpty("because token should have been correctly decoded with the valid base64 encoder");
        }
Пример #30
0
        public void Decode_With_VerifySignature_With_Byte_Multiple_Secrets_Empty_One_Should_Throw_Exception()
        {
            Action action =
                () => JwtBuilder.Create()
                .WithAlgorithm(TestData.HMACSHA256Algorithm)
                .WithSecret(new byte[0], new byte[1])
                .MustVerifySignature()
                .Decode(TestData.Token);

            action.Should()
            .Throw <ArgumentOutOfRangeException>("because secrets can't be empty");
        }