예제 #1
0
            public static T ReadToken <T>(string token, string secret)
            {
                var json = new JwtBuilder()
                           .WithAlgorithm(new HMACSHA256Algorithm())
                           .WithSecret(secret)
                           .MustVerifySignature()
                           .Decode(token);

                return(JsonConvert.DeserializeObject <T>(json));
            }
예제 #2
0
        public static string GenerateToken()
        {
            string secret = RandomString(30);
            string token  = new JwtBuilder()
                            .WithAlgorithm(new HMACSHA256Algorithm())
                            .WithSecret(secret)
                            .Encode();

            return(token);
        }
        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);
        }
예제 #4
0
        public ClaimsPrincipal GetPrincipal(string AuthenticationType, string token)
        {
            var json = new JwtBuilder()
                       .WithSecret(this.Secret)
                       .MustVerifySignature()
                       .Decode <IDictionary <string, string> >(token);
            var claimsIdentity = new ClaimsIdentity(json.Select(m => new Claim(m.Key, m.Value)), AuthenticationType);

            return(new ClaimsPrincipal(claimsIdentity));
        }
예제 #5
0
        public void Build_WithoutDependencies_Should_Throw_Exception()
        {
            var builder = new JwtBuilder();

            Action buildWithoutDependencies =
                () => builder.Build();

            buildWithoutDependencies.Should()
            .Throw <InvalidOperationException>("because a JWT can't be built without dependencies");
        }
예제 #6
0
        public void Decode_Should_Return_Token()
        {
            var builder = new JwtBuilder();

            var token = builder.WithAlgorithm(TestData.RS256Algorithm)
                        .Decode(TestData.Token);

            token.Should()
            .NotBeNullOrEmpty("because the decoded token contains values and they should have been decoded");
        }
예제 #7
0
        public void DecodeHeader_Should_Return_Header()
        {
            var builder = new JwtBuilder();

            var header = builder.WithAlgorithm(TestData.RS256Algorithm)
                         .DecodeHeader(TestData.TokenByAsymmetricAlgorithm);

            header.Should()
            .NotBeNullOrEmpty("because decoding header should be possible without validator or algorithm");
        }
예제 #8
0
        public void DecodeToken()
        {
            var builder = new JwtBuilder();

            var payload = builder.WithAlgorithm(TestData.HMACSHA256Algorithm)
                          .Decode(TestData.Token);

            payload.Should()
            .NotBeEmpty("because the decoded TestData.Token contains values and they should have been fetched");
        }
예제 #9
0
        public void DecodeToken_WithoutToken_Should_Throw_Exception()
        {
            var builder = new JwtBuilder();

            Action decodingANullJwt =
                () => builder.Decode(null);

            decodingANullJwt.Should()
            .Throw <ArgumentException>("because null is not a valid value for a token");
        }
예제 #10
0
            public static string BuildToken(Dictionary <string, string> claims, string secret)
            {
                var builder = new JwtBuilder()
                              .WithAlgorithm(new HMACSHA256Algorithm())
                              .WithSecret(secret);

                claims.ToList().ForEach(claim => builder.AddClaim(claim.Key, claim.Value));

                return(builder.Encode());
            }
        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);
        }
예제 #12
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            // TODO: key應該移至config
            if (actionContext.Request.Headers.Authorization == null || actionContext.Request.Headers.Authorization.Scheme != "Bearer")
            {
                setErrorResponse(actionContext, "沒有看到存取權杖錯誤");
            }
            else
            {
                try
                {
                    #region 進行存取權杖的解碼
                    string secretKey = MainHelper.SecretKey;
                    var    json      = new JwtBuilder()
                                       .WithAlgorithm(new HMACSHA256Algorithm())
                                       .WithSecret(secretKey)
                                       .MustVerifySignature()
                                       .Decode <Dictionary <string, object> >(actionContext.Request.Headers.Authorization.Parameter);
                    #endregion

                    #region 將存取權杖所夾帶的內容取出來
                    var fooRole     = json["role"] as Newtonsoft.Json.Linq.JArray;
                    var fooRoleList = fooRole.Select(x => (string)x).ToList <string>();
                    #endregion

                    #region 將存取權杖的夾帶欄位,儲存到 HTTP 要求的屬性
                    actionContext.Request.Properties.Add("user", json["iss"] as string);
                    actionContext.Request.Properties.Add("role", fooRoleList);
                    #endregion

                    #region 設定目前 HTTP 要求的安全性資訊
                    var fooPrincipal =
                        new GenericPrincipal(new GenericIdentity(json["iss"] as string, "MyPassport"), fooRoleList.ToArray());
                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.User = fooPrincipal;
                    }
                    #endregion
                }
                catch (TokenExpiredException)
                {
                    setErrorResponse(actionContext, "權杖已經逾期");
                }
                catch (SignatureVerificationException)
                {
                    setErrorResponse(actionContext, "權杖似乎不正確,沒有正確的數位簽名");
                }
                catch (Exception ex)
                {
                    setErrorResponse(actionContext, $"權杖解析發生異常 : {ex.Message}");
                }
            }

            base.OnAuthorization(actionContext);
        }
예제 #13
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);
        }
예제 #14
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");
        }
예제 #15
0
        public void Decode_With_VerifySignature_Should_Return_Token_When_Algorithm_Is_Symmetric()
        {
            var token = JwtBuilder.Create()
                        .WithAlgorithm(TestData.HMACSHA256Algorithm)
                        .WithSecret(TestData.Secret)
                        .MustVerifySignature()
                        .Decode(TestData.Token);

            token.Should()
            .NotBeNullOrEmpty("because the signature must have been verified successfully and the JWT correctly decoded");
        }
예제 #16
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");
        }
예제 #17
0
        public static string GenerateToken(string username, int expireMinutes = 60)
        {
            var token = new JwtBuilder()
                        .WithAlgorithm(new HMACSHA256Algorithm())
                        .WithSecret(Secret)
                        .AddClaim("exp", DateTimeOffset.UtcNow.AddMinutes(expireMinutes).ToUnixTimeSeconds())
                        .AddClaim("username", username)
                        .Encode();

            return(token);
        }
예제 #18
0
        public string JwtToken(string id)
        {
            var token = new JwtBuilder()
                        .WithAlgorithm(new HMACSHA256Algorithm())
                        .WithSecret(jwtkey)
                        .AddClaim("exp", DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds())
                        .AddClaim(Jwt_AccountId, id)
                        .Build();

            return(token);
        }
예제 #19
0
        public static string CreateJWT(int userId, int time)
        {
            var token = new JwtBuilder()
                        .WithAlgorithm(new HMACSHA256Algorithm())
                        .WithSecret("GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk")
                        .AddClaim("exp", DateTimeOffset.UtcNow.AddHours(time).ToUnixTimeSeconds())
                        .AddClaim("userId", userId)
                        .Encode();

            return(token);
        }
예제 #20
0
        public string Generate(Dictionary <string, object> payload)
        {
            var token = new JwtBuilder()
                        .WithAlgorithm(new HMACSHA512Algorithm())
                        .WithSecret(_config.Value.Secret)
                        .AddClaim("exp", DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds())
                        .AddClaims(payload.ToList())
                        .Encode();

            return(token);
        }
예제 #21
0
        internal string NewSession(TSession sessionData)
        {
            var token = new JwtBuilder()
                        .WithSecret(_settings.Secret)
                        .WithAlgorithm(_settings.Algorithm)
                        .AddClaim("exp", DateTimeOffset.UtcNow.Add(_settings.SessionLength).ToUnixTimeSeconds())
                        .AddClaim("data", sessionData)
                        .Build();

            return($"Bearer {token}");
        }
예제 #22
0
        /// <summary>
        /// Extension to any object. It will create a JWT Token with Json of the main object that will last for ExpiryMinutes
        /// </summary>
        /// <param name="obj">Any object</param>
        /// <param name="ExpiryMinutes">How long token stays valid</param>
        /// <returns>JWT Token</returns>
        public static string GenerateToken(this object obj, int ExpiryMinutes)
        {
            var token = new JwtBuilder()
                        .WithAlgorithm(_Algorithm)
                        .WithSecret(_Secret)
                        .AddClaim("exp", DateTimeOffset.UtcNow.AddMinutes(ExpiryMinutes).ToUnixTimeSeconds())
                        .AddClaim("sub", new JsonNetSerializer().Serialize(obj))
                        .Build();

            return(token);
        }
        public static string GetProjectIdFromRequest(HttpRequest httpRequest)
        {
            if (httpRequest.Headers.ContainsKey("Authorization"))
            {
                string  payload     = new JwtBuilder().Decode(httpRequest.Headers["Authorization"]);
                JObject payloadJObj = JObject.Parse(payload);
                return((string)payloadJObj["aud"]);
            }

            return(null);
        }
예제 #24
0
 public static JwtBuilder AddClaims(this JwtBuilder builder, PinAuth pinPayload)
 {
     return(builder
            .AddClaim("client_id", pinPayload.client_id)
            .AddClaim("device_id", pinPayload.device_id)
            .AddClaim("credential", pinPayload.credential)
            .AddClaim("credential_type", pinPayload.credential_type)
            .AddClaim("nonce", pinPayload.nonce)
            .AddClaim("timestamp", pinPayload.timestamp)
            .AddClaim("scope", pinPayload.scope));
 }
예제 #25
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");
        }
        private string CreateToken(string username)
        {
            var token = new JwtBuilder()
                        .WithAlgorithm(new HMACSHA256Algorithm())
                        .WithSecret(clientSecret)
                        .AddClaim("exp", DateTimeOffset.UtcNow.AddHours(8).ToUnixTimeSeconds())
                        .AddClaim("user", username)
                        .Build();

            return(token);
        }
예제 #27
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");
        }
        private static TimeSpan _expiresIn(string accessToken)
        {
            var decode = new JwtBuilder()
                         .DoNotVerifySignature()
                         .WithAlgorithm(new HMACSHA256Algorithm())
                         .Decode <IDictionary <string, object> >(accessToken);

            var res = DateTimeOffset.FromUnixTimeSeconds((long)decode["exp"]) - DateTimeOffset.UtcNow;

            return(res);
        }
예제 #29
0
        private void CreateToken()
        {
            var token = JwtBuilder.Create()
                        .WithAlgorithm(new HMACSHA256Algorithm()) // symmetric
                        .WithSecret(Secret)
                        .AddClaim("exp", Expire)
                        .AddClaim("userId", UserId)
                        .Encode();

            Token = token;
        }
예제 #30
0
        public async Task <LoginRequestResponse> Handle(LoginRequest request, CancellationToken cancellationToken)
        {
            var user = await _userService.GetByName(request.UserName);

            var token = JwtBuilder.CreateUserToken(user, _appConfigurations);

            return(new LoginRequestResponse()
            {
                Token = token
            });
        }