/// <summary>
        /// Retrieves the signing credential (override to load key from alternative locations)
        /// </summary>
        /// <returns>The signing credential</returns>
        protected virtual async Task <SigningCredentials> GetSigningCredentialsAsync()
        {
            var key = await _keyService.GetSigningKeyAsync();

            var certificate = await _certificateKeyService.GetCertificate(key);

            return(new X509SigningCredentials(certificate));
        }
Example #2
0
        private async Task <TokenValidationResult> ValidateJwtAsync(string jwt, string audience, IEnumerable <JsonWebKey> signingKeys, bool validateLifetime = true)
        {
            var handler = new JwtSecurityTokenHandler
            {
                Configuration =
                    new SecurityTokenHandlerConfiguration
                {
                    CertificateValidationMode = X509CertificateValidationMode.None,
                    CertificateValidator      = X509CertificateValidator.None
                }
            };

            var signingCertificates = await Task.WhenAll(signingKeys.Select(key => _certificateKeyService.GetCertificate(key)));

            var keys = (from c in signingCertificates select new X509SecurityKey(c)).ToList();

            var parameters = new TokenValidationParameters
            {
                ValidIssuer       = IssuerUri,
                IssuerSigningKeys = keys,
                ValidateLifetime  = validateLifetime,
                ValidAudience     = audience
            };

            try
            {
                SecurityToken jwtToken;
                var           id = handler.ValidateToken(jwt, parameters, out jwtToken);

                // if access token contains an ID, log it
                var jwtId = id.FindFirst(Constants.ClaimTypes.JwtId);
                if (jwtId != null)
                {
                    _log.JwtId = jwtId.Value;
                }

                // load the client that belongs to the client_id claim
                Client client   = null;
                var    clientId = id.FindFirst(Constants.ClaimTypes.ClientId);
                if (clientId != null)
                {
                    client = await _clients.FindClientByIdAsync(clientId.Value);

                    if (client == null)
                    {
                        throw new InvalidOperationException("Client does not exist anymore.");
                    }
                }

                return(new TokenValidationResult
                {
                    IsError = false,

                    Claims = id.Claims,
                    Client = client,
                    Jwt = jwt
                });
            }
            catch (Exception ex)
            {
                Logger.ErrorException("JWT token validation error", ex);
                return(Invalid(Constants.ProtectedResourceErrors.InvalidToken));
            }
        }