public virtual ClaimsPrincipal ValidateToken(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return(null);
            }

            ClaimsPrincipal  principal = null;
            JwtSecurityToken validJwt  = null;

            try
            {
                principal = _handler.ValidateToken(token, Options.TokenValidationParameters, out SecurityToken validatedToken);
                validJwt  = validatedToken as JwtSecurityToken;
            }
            catch (Exception ex)
            {
                _logger?.LogError("ValidateToken failed: " + ex.Message);
                ThrowJwtException(ex.Message, "invalid_token");
            }

            if (validJwt == null || principal == null)
            {
                ThrowJwtException(null, "invalid_token");
            }

// an exception has already been thrown if principal is null
#pragma warning disable S2259 // Null pointers should not be dereferenced
            CloudFoundryJwt.OnTokenValidatedAddClaims((ClaimsIdentity)principal.Identity, validJwt);
#pragma warning restore S2259 // Null pointers should not be dereferenced

            bool validScopes = ValidateScopes(validJwt);
            if (!validScopes)
            {
                ThrowJwtException(null, "insufficient_scope");
            }

            return(principal);
        }
Exemplo n.º 2
0
        public virtual ClaimsPrincipal ValidateToken(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return(null);
            }

            SecurityToken    validatedToken = null;
            ClaimsPrincipal  principal      = null;
            JwtSecurityToken validJwt       = null;

            try
            {
                principal = _handler.ValidateToken(token, Options.TokenValidationParameters, out validatedToken);
                validJwt  = validatedToken as JwtSecurityToken;
            }
            catch (Exception ex)
            {
                _logger?.LogError("ValidateToken failed: " + ex.Message);
                ThrowJwtException(ex.Message, "invalid_token");
            }

            if (validJwt == null || principal == null)
            {
                ThrowJwtException(null, "invalid_token");
            }

            CloudFoundryJwt.OnTokenValidatedAddClaims((ClaimsIdentity)principal.Identity, validJwt);

            bool validScopes = ValidateScopes(validJwt);

            if (!validScopes)
            {
                ThrowJwtException(null, "insufficient_scope");
            }

            return(principal);
        }