예제 #1
0
        public static void Authenticate(string token, string issuer, string audience, string signingKey)
        {
            try
            {
                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey         = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Convert.FromBase64String(signingKey)),
                    ValidIssuer              = issuer,
                    ValidAudience            = audience,
                    ValidateAudience         = true,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true
                };

                Microsoft.IdentityModel.Tokens.SecurityToken stoken = null;

                Thread.CurrentPrincipal = tokenHandler.ValidateToken(token, validationParameters, out stoken);
            }
            catch (Microsoft.IdentityModel.Tokens.SecurityTokenValidationException e)
            {
                Trace.TraceWarning("JWT validation has security token exception.");
                Trace.TraceError(e.Message);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Exception in JWT validation.");
                Trace.TraceError(ex.Message);
            }
        }
        //string token, SecurityToken securityToken, string kid, TokenValidationParameters validationParameter
        private static IEnumerable <SecurityKey> ResolveRsaKeys(
            string token,
            SecurityToken securityToken,
            string kid,
            TokenValidationParameters validationParameters)
        {
            //string id = null;
            //foreach (var keyId in keyIdentifier)
            //{
            //    var nk = keyId as NamedKeySecurityKeyIdentifierClause;
            //    if (nk != null)
            //    {
            //        id = nk.Id;
            //        break;
            //    }
            //}

            //if (id == null) return null;

            var keys = validationParameters.IssuerSigningKeys.Where(it => it.KeyId == kid);

            //if (issuerToken == null) return null;

            return(keys);
        }
예제 #3
0
        public static bool TryIssueToken
        (
            string issuer
            , string audience
            , IEnumerable <Claim> claims
            , string plainTextSecurityKey
            , out Microsoft.IdentityModel.Tokens.SecurityToken plainToken
            , out string secretTokenString
            , string signingCredentialsAlgorithm  = Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature
            , string signingCredentialsDigest     = Microsoft.IdentityModel.Tokens.SecurityAlgorithms.Sha256Digest
            , string plainTextSecurityKeyEncoding = "UTF-8"
        )
        {
            bool r = false;

            plainToken        = null;
            secretTokenString = null;
            try
            {
                var signingKey = new Microsoft
                                 .IdentityModel
                                 .Tokens
                                 .SymmetricSecurityKey
                                 (
                    Encoding
                    .GetEncoding(plainTextSecurityKeyEncoding)
                    .GetBytes(plainTextSecurityKey)
                                 );
                var signingCredentials
                    = new Microsoft
                      .IdentityModel
                      .Tokens
                      .SigningCredentials
                      (
                          signingKey
                          , signingCredentialsAlgorithm
                          , signingCredentialsDigest
                      );
                r = TryIssueToken
                    (
                    issuer
                    , audience
                    , claims
                    , out plainToken
                    , out secretTokenString
                    , signingKey
                    , signingCredentials
                    );
            }
            catch //(Exception)
            {
                //throw;
            }
            return
                (r);
        }
예제 #4
0
 public bool LifetimeValidator(DateTime?notBefore, DateTime?expires, Microsoft.IdentityModel.Tokens.SecurityToken securityToken, TokenValidationParameters validationParameters)
 {
     if (expires != null)
     {
         if (DateTime.UtcNow < expires)
         {
             return(true);
         }
     }
     return(false);
 }
예제 #5
0
        public static bool TryIssueToken
        (
            string issuer
            , string audience
            , JObject jClaimsIdentity
            , string plainTextSecurityKey
            , out Microsoft.IdentityModel.Tokens.SecurityToken plainToken
            , out string secretTokenString
            , string signingCredentialsAlgorithm  = Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature
            , string signingCredentialsDigest     = Microsoft.IdentityModel.Tokens.SecurityAlgorithms.Sha256Digest
            , string plainTextSecurityKeyEncoding = "UTF-8"
        )
        {
            var jValues = jClaimsIdentity
                          .GetAllJValues();
            var claims = jValues
                         .Select
                         (
                (x) =>
            {
                var value = string.Empty;
                var key   = x.Path;
                if (_claimTypes.TryGetValue(key, out value))
                {
                    key = value;
                }
                else
                {
                    key = x.Path;
                }
                return
                (new Claim
                 (
                     key
                     , x.Value.ToString()
                 ));
            }
                         );
            var r = TryIssueToken
                    (
                issuer
                , audience
                , claims
                , plainTextSecurityKey
                , out plainToken
                , out secretTokenString
                , signingCredentialsAlgorithm
                , signingCredentialsDigest
                , plainTextSecurityKeyEncoding
                    );

            return(r);
        }
        private static IEnumerable <SecurityKey> ResolveRsaKeys(
            string token,
            SecurityToken securityToken,
            string kid,
            TokenValidationParameters validationParameters)
        {
            var id = kid ?? securityToken?.SecurityKey?.KeyId;

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

            return(validationParameters.IssuerSigningKeys.Where(it => it.KeyId == id));
        }
예제 #7
0
        public static bool TryValidateToken
        (
            string plainTextSecurityKey
            , string token
            , string[] issuers
            , string[] audiences
            , out Microsoft.IdentityModel.Tokens.SecurityToken validatedToken
            , out ClaimsPrincipal claimsPrincipal
        )
        {
            var r = false;

            validatedToken  = null;
            claimsPrincipal = null;
            try
            {
                var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(plainTextSecurityKey));
                var tokenValidationParameters = new TokenValidationParameters()
                {
                    ValidAudiences   = audiences,
                    ValidIssuers     = issuers,
                    IssuerSigningKey = signingKey
                };
                var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
                var jst          = ((JwtSecurityToken)tokenHandler.ReadToken(token));
                claimsPrincipal = tokenHandler
                                  .ValidateToken
                                  (
                    token
                    , tokenValidationParameters
                    , out validatedToken
                                  );
                r = true;
            }
            catch (Exception e)
            {
                Console.WriteLine();
            }
            return(r);
        }
예제 #8
0
        public static string GenerateToken(string username)
        {
            var symmetricKey    = Convert.FromBase64String(Secret);
            var tokenHandler    = new JwtSecurityTokenHandler();
            int expireMinutes   = TokenExpiration;
            var now             = DateTime.UtcNow;
            var tokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, username)
                }),

                Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),

                SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(symmetricKey), Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature)
            };

            Microsoft.IdentityModel.Tokens.SecurityToken securityToken = tokenHandler.CreateToken(tokenDescriptor);
            var token = tokenHandler.WriteToken(securityToken);

            return(token);
        }
예제 #9
0
        private static bool ValidateJwt(string tokenString, string signingKey, string issuer = null, string audience = null, HttpContext context = null)
        {
            try
            {
                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey         = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Convert.FromBase64String(signingKey)),
                    ValidIssuer              = issuer,
                    ValidAudience            = audience,
                    ValidateAudience         = audience != null,
                    ValidateIssuer           = issuer != null,
                    ValidateIssuerSigningKey = true
                };

                Microsoft.IdentityModel.Tokens.SecurityToken stoken = null;

                ClaimsPrincipal prin = tokenHandler.ValidateToken(tokenString, validationParameters, out stoken);
                if (context == null)
                {
                    Thread.CurrentPrincipal = prin;
                }
                else
                {
                    context.User.AddIdentity(prin.Identity as ClaimsIdentity);
                }

                return(true);
            }
            catch (Exception ex)
            {
                Trace.TraceError("JWT validation exception {0}", ex.Message);
                return(false);
            }
        }
        public static bool TryIssueToken
        (
            string issuer
            , string audience
            , string userName
            , IEnumerable <Claim> claims
            , out Microsoft
            .IdentityModel
            .Tokens
            .SecurityToken plainToken
            , out string secretTokenString
            , Microsoft
            .IdentityModel
            .Tokens
            .SymmetricSecurityKey
            signingKey
            , Microsoft
            .IdentityModel
            .Tokens
            .SigningCredentials
            signingCredentials
            //, IIdentity identity = null
        )
        {
            bool r = false;

            plainToken        = null;
            secretTokenString = null;
            try
            {
                IIdentity user = new JsonWebTokenUser
                                 (
                    userName
                    , "jwt"
                    , true
                                 );
                var claimsIdentity          = new ClaimsIdentity(user, claims);
                var securityTokenDescriptor =
                    new Microsoft
                    .IdentityModel
                    .Tokens
                    .SecurityTokenDescriptor()
                {
                    Issuer             = issuer,
                    Audience           = audience,
                    IssuedAt           = DateTime.Now,
                    Subject            = claimsIdentity,
                    SigningCredentials = signingCredentials,
                };
                var tokenHandler = new System
                                   .IdentityModel
                                   .Tokens
                                   .Jwt
                                   .JwtSecurityTokenHandler();
                plainToken        = tokenHandler.CreateToken(securityTokenDescriptor);
                secretTokenString = tokenHandler.WriteToken(plainToken);
                r = true;
            }
            catch (Exception e)
            {
                //throw;
            }
            return
                (r);
        }
예제 #11
0
        public static bool TryIssueToken
        (
            string issuer
            , string audience
            , IEnumerable <Claim> claims
            , out Microsoft.IdentityModel.Tokens.SecurityToken plainToken
            , out string secretTokenString
            , Microsoft
            .IdentityModel
            .Tokens
            .SymmetricSecurityKey
            signingKey
            , Microsoft
            .IdentityModel
            .Tokens
            .SigningCredentials
            signingCredentials
        )
        {
            bool r = false;

            plainToken        = null;
            secretTokenString = null;
            try
            {
                //var signingKey = new Microsoft
                //                           .IdentityModel
                //                           .Tokens
                //                           .SymmetricSecurityKey
                //                                   (
                //                                       Encoding
                //                                           .GetEncoding(plainTextSecurityKeyEncoding)
                //                                           .GetBytes(plainTextSecurityKey)
                //                                   );
                //var signingCredentials
                //            = new Microsoft.IdentityModel.Tokens.SigningCredentials
                //                (
                //                    signingKey
                //                    , signingCredentialsAlgorithm
                //                    , signingCredentialsDigest
                //                );
                // ComplexClaim
                var claimsIdentity = new ClaimsIdentity
                                     (
                    claims
                    , "Custom"
                                     );
                var securityTokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
                {
                    Issuer             = issuer,
                    Audience           = audience,
                    IssuedAt           = DateTime.Now,
                    Subject            = claimsIdentity,
                    SigningCredentials = signingCredentials,
                };

                var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
                plainToken        = tokenHandler.CreateToken(securityTokenDescriptor);
                secretTokenString = tokenHandler.WriteToken(plainToken);
                r = true;
            }
            catch //(Exception)
            {
                //throw;
            }
            return
                (r);
        }
예제 #12
0
 //private static bool AudienceValidator_(IEnumerable<string> audiences, SystemIdentityModelToken.SecurityToken securityToken, SystemIdentityModelToken.TokenValidationParameters validationParameters)
 private static bool AudienceValidator_(IEnumerable <string> audiences, MicrosoftIdentityModelToken.SecurityToken securityToken, MicrosoftIdentityModelToken.TokenValidationParameters validationParameters)
 {
     return(true);
 }
예제 #13
0
        // Override and build our own logic. The problem is ValidateTokenReplay that serializes the token back. And that
        // breaks because it expects some optional values to be present.
        public override ClaimsPrincipal ValidateToken(string token, TokenValidationParameters validationParameters, out Microsoft.IdentityModel.Tokens.SecurityToken validatedToken)
        {
            var samlToken = ReadSaml2Token(token);

            ValidateConditions(samlToken, validationParameters);
            ValidateSubject(samlToken, validationParameters);

            var issuer = ValidateIssuer(samlToken.Issuer, samlToken, validationParameters);

            // Just using the assertion id for token replay. As that is part of the signed value it cannot
            // be altered by someone replaying the token.
            ValidateTokenReplay(samlToken.Assertion.Conditions.NotOnOrAfter, samlToken.Assertion.Id.Value, validationParameters);

            // ValidateIssuerSecurityKey not called - we have our own signature validation.

            validatedToken = samlToken;
            var identity = CreateClaimsIdentity(samlToken, issuer, validationParameters);

            if (validationParameters.SaveSigninToken)
            {
                identity.BootstrapContext = samlToken;
            }

            return(new ClaimsPrincipal(identity));
        }
예제 #14
0
        /// <summary>
        /// Determines if the audiences found in a <see cref="SecurityToken"/> are valid.
        /// </summary>
        /// <param name="audiences">The audiences found in the <see cref="SecurityToken"/>.</param>
        /// <param name="securityToken">The <see cref="SecurityToken"/> being validated.</param>
        /// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
        /// <exception cref="ArgumentNullException">If 'vaidationParameters' is null.</exception>
        /// <exception cref="ArgumentNullException">If 'audiences' is null and <see cref="TokenValidationParameters.ValidateAudience"/> is true.</exception>
        /// <exception cref="SecurityTokenInvalidAudienceException">If <see cref="TokenValidationParameters.ValidAudience"/> is null or whitespace and <see cref="TokenValidationParameters.ValidAudiences"/> is null.</exception>
        /// <exception cref="SecurityTokenInvalidAudienceException">If none of the 'audiences' matched either <see cref="TokenValidationParameters.ValidAudience"/> or one of <see cref="TokenValidationParameters.ValidAudiences"/>.</exception>
        /// <remarks>An EXACT match is required.</remarks>
        public static void ValidateAudience(IEnumerable <string> audiences, SecurityToken securityToken, TokenValidationParameters validationParameters)
        {
            if (validationParameters == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(validationParameters));
            }

            if (!validationParameters.ValidateAudience)
            {
                LogHelper.LogWarning(LogMessages.IDX10233);
                return;
            }

            if (validationParameters.AudienceValidator != null)
            {
                if (!validationParameters.AudienceValidator(audiences, securityToken, validationParameters))
                {
                    throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidAudienceException(LogHelper.FormatInvariant(LogMessages.IDX10231, securityToken))
                    {
                        InvalidAudience = Utility.SerializeAsSingleCommaDelimitedString(audiences)
                    });
                }

                return;
            }

            if (audiences == null)
            {
                throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidAudienceException(LogMessages.IDX10207)
                {
                    InvalidAudience = null
                });
            }

            if (string.IsNullOrWhiteSpace(validationParameters.ValidAudience) && (validationParameters.ValidAudiences == null))
            {
                throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidAudienceException(LogMessages.IDX10208)
                {
                    InvalidAudience = Utility.SerializeAsSingleCommaDelimitedString(audiences)
                });
            }

            foreach (string audience in audiences)
            {
                if (string.IsNullOrWhiteSpace(audience))
                {
                    continue;
                }

                if (validationParameters.ValidAudiences != null)
                {
                    foreach (string str in validationParameters.ValidAudiences)
                    {
                        if (string.Equals(audience, str, StringComparison.Ordinal))
                        {
                            LogHelper.LogInformation(LogMessages.IDX10234, audience);
                            return;
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(validationParameters.ValidAudience))
                {
                    if (string.Equals(audience, validationParameters.ValidAudience, StringComparison.Ordinal))
                    {
                        LogHelper.LogInformation(LogMessages.IDX10234, audience);
                        return;
                    }
                }
            }

            throw LogHelper.LogExceptionMessage(
                      new SecurityTokenInvalidAudienceException(LogHelper.FormatInvariant(LogMessages.IDX10214, Utility.SerializeAsSingleCommaDelimitedString(audiences), (validationParameters.ValidAudience ?? "null"), Utility.SerializeAsSingleCommaDelimitedString(validationParameters.ValidAudiences)))
            {
                InvalidAudience = Utility.SerializeAsSingleCommaDelimitedString(audiences)
            });
        }
예제 #15
0
        /// <summary>
        /// Determines if an issuer found in a <see cref="SecurityToken"/> is valid.
        /// </summary>
        /// <param name="issuer">The issuer to validate</param>
        /// <param name="securityToken">The <see cref="SecurityToken"/> that is being validated.</param>
        /// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
        /// <returns>The issuer to use when creating the "Claim"(s) in a "ClaimsIdentity".</returns>
        /// <exception cref="ArgumentNullException">If 'vaidationParameters' is null.</exception>
        /// <exception cref="ArgumentNullException">If 'issuer' is null or whitespace and <see cref="TokenValidationParameters.ValidateIssuer"/> is true.</exception>
        /// <exception cref="SecurityTokenInvalidIssuerException">If <see cref="TokenValidationParameters.ValidIssuer"/> is null or whitespace and <see cref="TokenValidationParameters.ValidIssuers"/> is null.</exception>
        /// <exception cref="SecurityTokenInvalidIssuerException">If 'issuer' failed to matched either <see cref="TokenValidationParameters.ValidIssuer"/> or one of <see cref="TokenValidationParameters.ValidIssuers"/>.</exception>
        /// <remarks>An EXACT match is required.</remarks>
        public static string ValidateIssuer(string issuer, SecurityToken securityToken, TokenValidationParameters validationParameters)
        {
            if (validationParameters == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(validationParameters));
            }

            if (!validationParameters.ValidateIssuer)
            {
                LogHelper.LogInformation(LogMessages.IDX10235);
                return(issuer);
            }

            if (validationParameters.IssuerValidator != null)
            {
                return(validationParameters.IssuerValidator(issuer, securityToken, validationParameters));
            }

            if (string.IsNullOrWhiteSpace(issuer))
            {
                throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidIssuerException(LogMessages.IDX10211)
                {
                    InvalidIssuer = issuer
                });
            }

            // Throw if all possible places to validate against are null or empty
            if (string.IsNullOrWhiteSpace(validationParameters.ValidIssuer) && (validationParameters.ValidIssuers == null))
            {
                throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidIssuerException(LogMessages.IDX10204)
                {
                    InvalidIssuer = issuer
                });
            }

            if (string.Equals(validationParameters.ValidIssuer, issuer, StringComparison.Ordinal))
            {
                LogHelper.LogInformation(LogMessages.IDX10236, issuer);
                return(issuer);
            }

            if (null != validationParameters.ValidIssuers)
            {
                foreach (string str in validationParameters.ValidIssuers)
                {
                    if (string.IsNullOrEmpty(str))
                    {
                        LogHelper.LogInformation(LogMessages.IDX10235);
                        continue;
                    }

                    if (string.Equals(str, issuer, StringComparison.Ordinal))
                    {
                        LogHelper.LogInformation(LogMessages.IDX10236, issuer);
                        return(issuer);
                    }
                }
            }

            throw LogHelper.LogExceptionMessage(
                      new SecurityTokenInvalidIssuerException(LogHelper.FormatInvariant(LogMessages.IDX10205, issuer, (validationParameters.ValidIssuer ?? "null"), Utility.SerializeAsSingleCommaDelimitedString(validationParameters.ValidIssuers)))
            {
                InvalidIssuer = issuer
            });
        }