예제 #1
0
        private bool VerifyToken(string token)
        {
            TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:SecretKey"])),
                ValidAudience    = _config["Jwt:Audience"],
                ValidIssuer      = _config["Jwt:Issuer"],
            };

            try
            {
                var claimPrinciple  = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out var securityKey);
                var expirationClaim = claimPrinciple.FindFirst(JwtRegisteredClaimNames.Exp);
                var jtiClaim        = claimPrinciple.FindFirst(JwtRegisteredClaimNames.Jti);
                if (jtiClaim is null || jtiClaim.Value is null)
                {
                    return(false);
                }

                var expiration = int.Parse(expirationClaim.Value);
                var authTime   = DateTimeUtilities.FromUnixTime(expiration);
                if (authTime < DateTime.UtcNow)
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
        /// <inheritdoc/>
        public Guid Validate(string token, TokenType tokenType)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new BadRequestException("Token can not be empty.");
            }

            try
            {
                var validationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = _options.Value.TokenIssuer,
                    ValidateAudience         = true,
                    ValidAudience            = _options.Value.TokenAudience,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = _decodingKey.GetKey(),
                    ValidateIssuerSigningKey = true
                };

                ClaimsPrincipal claims              = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out _);
                var             userIdClaimValue    = claims.FindFirst("UserId")?.Value;
                var             tokenTypeClaimValue = claims.FindFirst("TokenType")?.Value;
                if (string.IsNullOrEmpty(userIdClaimValue) ||
                    !Guid.TryParse(userIdClaimValue, out Guid userId) ||
                    tokenType.ToString() != tokenTypeClaimValue)
                {
                    throw new SecurityTokenValidationException("Bad token format.");
                }

                return(userId);
            }
            catch (SecurityTokenValidationException exc)
            {
                string message = "Token failed validation.";

                _logger.LogInformation($"{message}{Environment.NewLine}{exc}");

                throw new ForbiddenException(message);
            }
            catch (Exception exc)
            {
                string message = "Token format was wrong.";

                _logger.LogInformation($"{message}{Environment.NewLine}{exc}");

                throw new BadRequestException(message);
            }
        }
        private async Task <List <Claim> > ValidateToken(string token)
        {
            await LoadConfig();

            var tokens = new List <X509SecurityToken>(
                from key in _config.JsonWebKeySet.Keys
                select new X509SecurityToken(new X509Certificate2(Convert.FromBase64String(key.X5c.First()))));

            var parameters = new TokenValidationParameters
            {
                ValidIssuer = _stsServer,
                ValidateIssuerSigningKey = true,
                IssuerSigningTokens      = tokens
            };

            SecurityToken jwt;
            var           principal = new JwtSecurityTokenHandler().ValidateToken(token, parameters, out jwt);

            // validate nonce
            var nonceClaim = principal.FindFirst("nonce");

            if (!string.Equals(nonceClaim.Value, nonceClaim.ToString(), StringComparison.Ordinal))
            {
                throw new Exception("invalid nonce");
            }
            return(principal.Claims.ToList());
        }
예제 #4
0
        /// <summary>
        /// Validate and return the user id associated with this token.
        /// Failures would occur if any of the issuer info, the expiration info is not matching.
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public string ValidateRegistrationToken(string token)
        {
            SecurityToken   validatedToken;
            ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(token, this.TokenValidationParams, out validatedToken);

            return(principal?.FindFirst(c => c.Type.Equals(ClaimTypes.Sid))?.Value);
        }
예제 #5
0
        private async Task <IEnumerable <Claim> > ValidateIdentityTokenAsync(string token, string state)
        {
            var result = await Request.GetOwinContext().Authentication.AuthenticateAsync("TempCookie");

            if (result == null)
            {
                throw new InvalidOperationException("No temp cookie");
            }

            if (state != result.Identity.FindFirst("state").Value)
            {
                throw new InvalidOperationException("invalid state");
            }

            var parameters = new TokenValidationParameters
            {
                AllowedAudience = "implicitclient",
                ValidIssuer     = "https://idsrv3.com",
                SigningToken    = new X509SecurityToken(X509.LocalMachine.TrustedPeople.SubjectDistinguishedName.Find("CN=idsrv3test", false).First())
            };

            var id = new JwtSecurityTokenHandler().ValidateToken(token, parameters);

            if (id.FindFirst("nonce").Value != result.Identity.FindFirst("nonce").Value)
            {
                throw new InvalidOperationException("Invalid nonce");
            }

            Request.GetOwinContext().Authentication.SignOut("TempCookie");
            return(id.Claims);
        }
예제 #6
0
        private List <Claim> ValidateToken(string token, string nonce)
        {
            var certString = "MIIDBTCCAfGgAwIBAgIQNQb+T2ncIrNA6cKvUA1GWTAJBgUrDgMCHQUAMBIxEDAOBgNVBAMTB0RldlJvb3QwHhcNMTAwMTIwMjIwMDAwWhcNMjAwMTIwMjIwMDAwWjAVMRMwEQYDVQQDEwppZHNydjN0ZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqnTksBdxOiOlsmRNd+mMS2M3o1IDpK4uAr0T4/YqO3zYHAGAWTwsq4ms+NWynqY5HaB4EThNxuq2GWC5JKpO1YirOrwS97B5x9LJyHXPsdJcSikEI9BxOkl6WLQ0UzPxHdYTLpR4/O+0ILAlXw8NU4+jB4AP8Sn9YGYJ5w0fLw5YmWioXeWvocz1wHrZdJPxS8XnqHXwMUozVzQj+x6daOv5FmrHU1r9/bbp0a1GLv4BbTtSh4kMyz1hXylho0EvPg5p9YIKStbNAW9eNWvv5R8HN7PPei21AsUqxekK0oW9jnEdHewckToX7x5zULWKwwZIksll0XnVczVgy7fCFwIDAQABo1wwWjATBgNVHSUEDDAKBggrBgEFBQcDATBDBgNVHQEEPDA6gBDSFgDaV+Q2d2191r6A38tBoRQwEjEQMA4GA1UEAxMHRGV2Um9vdIIQLFk7exPNg41NRNaeNu0I9jAJBgUrDgMCHQUAA4IBAQBUnMSZxY5xosMEW6Mz4WEAjNoNv2QvqNmk23RMZGMgr516ROeWS5D3RlTNyU8FkstNCC4maDM3E0Bi4bbzW3AwrpbluqtcyMN3Pivqdxx+zKWKiORJqqLIvN8CT1fVPxxXb/e9GOdaR8eXSmB0PgNUhM4IjgNkwBbvWC9F/lzvwjlQgciR7d4GfXPYsE1vf8tmdQaY8/PtdAkExmbrb9MihdggSoGXlELrPA91Yce+fiRcKY3rQlNWVd4DOoJ/cPXsXwry8pWjNCo5JD8Q+RQ5yZEy7YPoifwemLhTdsBz3hlZr28oCGJ3kbnpW0xGvQb3VHSTVVbeei0CfXoW6iz1";
            var cert       = new X509Certificate2(Convert.FromBase64String(certString));

            var parameters = new TokenValidationParameters
            {
                ValidAudience      = "codeclient",
                ValidIssuer        = Constants.BaseAddress,
                IssuerSigningToken = new X509SecurityToken(cert)
            };

            SecurityToken jwt;
            var           principal = new JwtSecurityTokenHandler().ValidateToken(token, parameters, out jwt);

            // validate nonce
            var nonceClaim = principal.FindFirst("nonce");

            if (!string.Equals(nonceClaim.Value, nonce, StringComparison.Ordinal))
            {
                throw new Exception("invalid nonce");
            }

            return(principal.Claims.ToList());
        }
예제 #7
0
        async Task <bool> ValidateToken(string token, string nonce)
        {
            var x509Str = await GetSigningCertAsync();

            var cert       = new X509Certificate2(Convert.FromBase64String(x509Str));
            var parameters = new TokenValidationParameters
            {
                ValidAudience = _urls.ClientId,
                ValidIssuers  = new List <string> {
                    _urls.BaseIdSrvUrl, "https://parcelfor.me", "https://dev.parcelfor.me"
                },
                IssuerSigningToken = new X509SecurityToken(cert)
            };

            SecurityToken jwt;
            var           principal = new JwtSecurityTokenHandler().ValidateToken(token, parameters, out jwt);

            // validate nonce
            var nonceClaim = principal.FindFirst("nonce");

            P4MHelpers.RemoveCookie(Response, "p4mNonce");
            if (!string.Equals(nonceClaim.Value, nonce, StringComparison.Ordinal))
            {
                throw new Exception("invalid nonce");
            }
            return(true);
        }
예제 #8
0
 public bool TokenVerify(AuthorizationFilterContext context)
 {
     try
     {
         if (!context.HttpContext.Request.Headers.ContainsKey("Authorization"))
         {
             return(false);
         }
         var token = context.HttpContext.Request.Headers["Authorization"].ToString();
         token = token.Replace("Bearer ", "");
         SecurityToken             validatedToken;
         TokenValidationParameters validationParameters = new TokenValidationParameters();
         validationParameters.IssuerSigningKey = JwtSecurityKey.Create("fiver-secret-key");
         validationParameters.ValidAudience    = "fiver.Security.Bearer";
         validationParameters.ValidIssuer      = "fiver.Security.Bearer";
         ClaimsPrincipal    principal         = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out validatedToken);
         Guid               userid            = principal.FindFirst("UserId").Value.ConvertGuid();
         IUserService       userService       = DependencyService.GetService <IUserService>();
         IMembershipManager membershipManager = DependencyService.GetService <IMembershipManager>();
         var user = membershipManager.UserFind(userid);
         return(_roleKeys.Select(roleKey => userService.IsUserAuthorized(user, roleKey)).Any(result => result));
     }
     catch (Exception)
     {
         return(false);
     }
 }
예제 #9
0
        public async Task <bool> ValidateTwoFactorRememberMeTokenAsync(ApplicationUser user, string token)
        {
            ClaimsPrincipal principal;
            SecurityToken   jwtToken;

            try
            {
                principal = new JwtSecurityTokenHandler().ValidateToken(token, GetValidationParameters(), out jwtToken);
            }
            catch (Exception e)
            {
                if (e is SecurityTokenException || e is ArgumentException)
                {
                    return(false);
                }
                throw;
            }

            if (jwtToken is not JwtSecurityToken)
            {
                throw new SecurityTokenException(nameof(jwtToken));
            }

            if (principal.FindFirst(JwtRegisteredClaimNames.Amr)?.Value != "otp")
            {
                return(false);
            }

            if (principal.FindFirst(JwtRegisteredClaimNames.Sub)?.Value != user.Id)
            {
                return(false);
            }

            if (principal.FindFirst(JwtRegisteredClaimNames.Email)?.Value != user.Email)
            {
                return(false);
            }

            if (principal.FindFirst("purpose")?.Value != "twoFactorRememberMe")
            {
                return(false);
            }

            return(true);
        }
예제 #10
0
        public string GetClaimValue(string claim, TokenValidationParameters tokenValidationParameters, string token)
        {
            var Token = Guard.Argument(token, nameof(token)).NotEmpty().NotNull().NotWhiteSpace();
            var Claim = Guard.Argument(claim, nameof(claim)).NotEmpty().NotNull().NotWhiteSpace();
            var TokenValidationParameters = Guard.Argument(tokenValidationParameters, nameof(tokenValidationParameters))
                                            .NotNull().Value;
            var claimsPrincipal = new JwtSecurityTokenHandler()
                                  .ValidateToken(Token, TokenValidationParameters, out var rawValidatedToken);

            return(claimsPrincipal.FindFirst(Claim).Value);
        }
예제 #11
0
        public int ValidateToken(string jwtToken)
        {
            TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                ValidateLifetime = true,
                ValidIssuer      = "PBlogsSite",
                ValidAudience    = "Subscriber",
                IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
            };
            ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(jwtToken.Remove(0, 7), validationParameters, out SecurityToken ValidateToken);

            return(Convert.ToInt32(principal?.FindFirst("ID")?.Value));
        }
예제 #12
0
        public void Does_Generate_Valid_Token()
        {
            // Arrange
            var claimId = "00000000-0000-0000-0000-000000000000";

            var provider             = TestHelper.CreateSecurityTokenProvider();
            var token                = provider.GenerateJwtToken(claimId);
            var validationParameters = provider.CreateTokenValidationParameters();

            // Act
            var principal = new JwtSecurityTokenHandler()
                            .ValidateToken(token, validationParameters, out _);

            // Assert
            Assert.Equal(claimId, principal.FindFirst(provider.ClaimType).Value);
        }
예제 #13
0
        public Claim GetClaimsFromToken(string token)
        {
            TokenValidationParameters validationParameters = new TokenValidationParameters()
            {
                RequireExpirationTime = true,
                IssuerSigningKey      = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes(_jwtSettings.JWTKey)
                    ),
                ValidateAudience = false,
                ValidateIssuer   = false
            };

            ClaimsPrincipal principal = new JwtSecurityTokenHandler()
                                        .ValidateToken(token, validationParameters, out SecurityToken validatedToken);

            return(principal.FindFirst(JwtRegisteredClaimNames.Jti));
        }
예제 #14
0
        private User FindUserByContext(HttpContext context)
        {
            var request = context.Request;
            var token   = request.Headers["Authorization"].ToString();

            token = token.Replace("Bearer ", "");
            SecurityToken             validatedToken;
            TokenValidationParameters validationParameters = new TokenValidationParameters();

            validationParameters.IssuerSigningKey = JwtSecurityKey.Create("fiver-secret-key");
            validationParameters.ValidAudience    = "fiver.Security.Bearer";
            validationParameters.ValidIssuer      = "fiver.Security.Bearer";
            ClaimsPrincipal    principal   = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out validatedToken);
            Guid               userid      = principal.FindFirst("UserId").Value.ConvertGuid();
            IMembershipManager userService = DependencyService.GetService <IMembershipManager>();
            var user = userService.UserFind(userid);

            return(user);
        }
        /*public string GetIdFromJwtToken(string jwtToken)
         * {
         *  var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("JWT_KEY")));
         *  var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
         *  var handler = new JwtSecurityTokenHandler();
         *  var validations = new TokenValidationParameters
         *  {
         *      ValidateIssuerSigningKey = true,
         *      IssuerSigningKey = new SymmetricSecurityKey(key),
         *      ValidateIssuer = true,
         *      ValidIssuer = Environment.GetEnvironmentVariable("JWT_ISSUER"),
         *      ValidateAudience = true,
         *      ValidAudience = Environment.GetEnvironmentVariable("JWT_ISSUER")
         *  };
         *  var claims = handler.ValidateToken(jwtToken, validations, out var tokenSecure);
         *  return claims.Claims<JwtRegisteredClaimNames>;
         * }*/

        public string ValidateToken(string jwtToken)
        {
            SecurityToken             validatedToken;
            TokenValidationParameters validationParameters = new TokenValidationParameters();

            validationParameters.ValidateLifetime = true;

            validationParameters.ValidAudience    = Environment.GetEnvironmentVariable("JWT_ISSUER");
            validationParameters.ValidIssuer      = Environment.GetEnvironmentVariable("JWT_ISSUER");
            validationParameters.IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("JWT_KEY")));
            try
            {
                ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(jwtToken, validationParameters, out validatedToken);
                return(principal.FindFirst("Sid").Value);
            }
            catch (Exception)
            {
                return("");
            }
        }
예제 #16
0
        private List <Claim> ValidateToken(string token, string nonce)
        {
            var validationParameters = new TokenValidationParameters
            {
                ValidIssuer       = OpenIdConfig.Config.Issuer,
                ValidAudiences    = new[] { OpenIdSettings.Settings.ClientId },
                IssuerSigningKeys = OpenIdConfig.Config.SigningKeys
            };

            SecurityToken jwt;
            var           principal = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out jwt);

            //validate nonce
            var nonceClaim = principal.FindFirst("nonce");

            if (!string.Equals(nonceClaim.Value, nonce, StringComparison.Ordinal))
            {
                throw new Exception("invalid nonce");
            }

            return(principal.Claims.ToList());
        }
예제 #17
0
        public static bool Validate(string token, out Dictionary <string, object> user)
        {
            TokenValidationParameters validationParameters =
                new TokenValidationParameters
            {
                ValidIssuer      = Environment.GetEnvironmentVariable(Config.TOKEN_ISSUE),
                ValidAudiences   = new[] { Environment.GetEnvironmentVariable(Config.TOKEN_ISSUE) },
                IssuerSigningKey = JwtConstants.SigningConfigurations.Key
            };
            var _user = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out SecurityToken validatedToken);

            if (_user.Identity.IsAuthenticated)
            {
                user = JsonConvert.DeserializeObject <Dictionary <string, object> >(_user.FindFirst("User").Value);
                return(true);
            }
            else
            {
                user = new Dictionary <string, object>();
                return(false);
            }
        }
        public string ValidateAndGetUsername(APIGatewayProxyRequest request, ILambdaContext context)
        {
            string authorization;

            if (!request.Headers.TryGetValue(AUTHORIZATION_HEADER, out authorization))
            {
                context.Logger.LogLine("Error, no Authorization header found");
                throw new Exception("Error, no Authorization header found");
            }

            if (authorization.StartsWith(BEARER_PREFIX, StringComparison.OrdinalIgnoreCase))
            {
                authorization = authorization.Substring(BEARER_PREFIX.Length + 1);
            }

            ClaimsPrincipal user;

            try
            {
                SecurityToken validatedToken;
                user = new JwtSecurityTokenHandler().ValidateToken(authorization, _jwtValidationParameters,
                                                                   out validatedToken);

                if (DateTime.UtcNow < validatedToken.ValidFrom || validatedToken.ValidTo < DateTime.UtcNow)
                {
                    Console.WriteLine(
                        $"Error, JWT Token expired. Token was valid from {validatedToken.ValidFrom} to {validatedToken.ValidTo}");
                    throw new Exception("JWT Token expired");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error validating JWT token: {e.Message}");
                throw;
            }

            return(user.FindFirst("cognito:username")?.Value);
        }
예제 #19
0
        public void JwtTokenValidationTest()
        {
            IdentityModelEventSource.ShowPII = true;
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            // Create JWT client authentication payload.
            var claims = new[] {
                new  Claim(JwtClaimTypes.Subject, ValidSubject),
            };
            var privateKey  = TEST_RSA_PrivateKey_256.ReadAsRSAKey();
            var cert        = new X509Certificate2(Convert.FromBase64String(TEST_X509_PublicKey_2048));
            var securityKey = new RsaSecurityKey(privateKey)
            {
                KeyId = cert.GetSubjectKeyIdentifier()
            };
            var signingCredentials = new SigningCredentials(new RsaSecurityKey(privateKey), SecurityAlgorithms.RsaSha256Signature);
            var token = new JwtSecurityToken(
                issuer: ValidIssuer,
                audience: ValidAudience,
                expires: DateTime.Now.AddMinutes(3),
                claims: claims,
                signingCredentials: signingCredentials
                );
            // End of custom claims.
            var jwt = new JwtSecurityTokenHandler().WriteToken(token);
            // Validate.
            var validationParameters = new TokenValidationParameters {
                IssuerSigningKey          = new X509SecurityKey(new X509Certificate2(Convert.FromBase64String(TEST_X509_PublicKey_2048))),
                ValidAudience             = ValidAudience,
                ValidIssuer               = ValidIssuer,
                ValidateIssuerSigningKey  = true,
                IssuerSigningKeyValidator = new Psd2IssuerSigningKeyValidator().Validate
            };
            var principal = new JwtSecurityTokenHandler().ValidateToken(jwt, validationParameters, out var validatedToken);

            Assert.Equal(ValidSubject, principal.FindFirst("sub").Value);
        }
예제 #20
0
        public async Task <string> GenerateJWTokenFromUserAsync(User user, string oldToken = null)
        {
            if (oldToken != null)
            {
                // Validate
                SecurityToken secTok;
                var           readToken = new JwtSecurityTokenHandler().ValidateToken(oldToken, new TokenValidationParameters
                {
                    ValidIssuer      = _config.GetSection("Jwt")["Issuer"],
                    ValidAudience    = _config.GetSection("Jwt")["Issuer"],
                    ValidateLifetime = false,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("Jwt")["Key"])),
                    ClockSkew        = TimeSpan.Zero // remove delay of token when expire
                }, out secTok);

                if (secTok == null)
                {
                    return(null);
                }

                var refreshToken = readToken.FindFirst("RefreshToken");
                // Check if valide
                var foundRefreshToken = await _context.UserSpecificTokens.SingleOrDefaultAsync(x => x.User.Id.Equals(user.Id) && x.Token.Equals(refreshToken.Value) && x.Type == UserSpecificTokenType.RefreshToken);

                if (foundRefreshToken == null)
                {
                    return(null);
                }

                // Delete old one
                if (!await DeleteRefreshTokenAsync(foundRefreshToken.Id))
                {
                    return(null);
                }
            }

            // Generate refresh token
            var newRefreshToken = await GenerateRefreshTokenAsync(user);

            if (newRefreshToken == null)
            {
                return(null);
            }

            var claims = new List <Claim>
            {
                new Claim("Name", user.UserName),
                new Claim("Guid", Guid.NewGuid().ToString()),
                new Claim("UserId", user.Id),
                new Claim("RefreshToken", newRefreshToken.Token)
            };

            var key     = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("Jwt")["Key"]));
            var creds   = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddMinutes(Convert.ToDouble(_config.GetSection("Jwt")["ExpireMinutes"]));

            var token = new JwtSecurityToken(
                _config.GetSection("Jwt")["Issuer"],
                _config.GetSection("Jwt")["Issuer"],
                claims,
                expires: expires,
                signingCredentials: creds
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }