<commit_before>﻿/*
 * Copyright 2014 <NAME>, <NAME>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Security.Claims;
using System.ServiceModel.Security;
using System.Threading.Tasks;
using Thinktecture.IdentityModel.Extensions;
using Thinktecture.IdentityServer.Core.Configuration;
using Thinktecture.IdentityServer.Core.Connect.Models;
using Thinktecture.IdentityServer.Core.Extensions;
using Thinktecture.IdentityServer.Core.Logging;
using Thinktecture.IdentityServer.Core.Services;

namespace Thinktecture.IdentityServer.Core.Connect
{
    public class TokenValidator
    {
        private readonly static ILog Logger = LogProvider.GetCurrentClassLogger();
        private readonly IdentityServerOptions _options;
        private readonly IUserService _users;
        private readonly ITokenHandleStore _tokenHandles;
        private readonly ICustomTokenValidator _customValidator;
        private readonly IClientStore _clients;

        public TokenValidator(IdentityServerOptions options, IUserService users, IClientStore clients, ITokenHandleStore tokenHandles, ICustomTokenValidator customValidator)
        {
            _options = options;
            _users = users;
            _clients = clients;
            _tokenHandles = tokenHandles;
            _customValidator = customValidator;
        }

        public virtual async Task<TokenValidationResult> ValidateIdentityTokenAsync(string token, string clientId, bool validateLifetime = true)
        {
            var result = await ValidateJwtAsync(token, clientId, validateLifetime);

            if (result.IsError)
            {
                return result;
            }

            Logger.Debug("Calling custom token validator");
            var customResult = await _customValidator.ValidateIdentityTokenAsync(result);

            if (customResult.IsError)
            {
                Logger.Error("Custom validator failed: " + customResult.Error ?? "unknown");
            }

            return customResult;
        }

        public virtual async Task<TokenValidationResult> ValidateAccessTokenAsync(string token, string expectedScope = null)
        {
            Logger.Info("Start access token validation");
            Logger.Debug("Token: " + token);

            TokenValidationResult result;

            if (token.Contains("."))
            {
                Logger.InfoFormat("Validating a JWT access token");
                result = await ValidateJwtAsync(token, string.Format(Constants.AccessTokenAudience, _options.IssuerUri));
            }
            else
            {
                Logger.InfoFormat("Validating a reference access token");
                result = await ValidateReferenceAccessTokenAsync(token);
            }

            if (result.IsError)
            {
                return result;
            }

            if (expectedScope.IsPresent())
            {
                var scope = result.Claims.FirstOrDefault(c => c.Type == Constants.ClaimTypes.Scope && c.Value == expectedScope);
                if (scope == null)
                {
                    Logger.InfoFormat("Checking for expected scope {0} failed", expectedScope);
                    return Invalid(Constants.ProtectedResourceErrors.InsufficientScope);
                }

                Logger.InfoFormat("Checking for expected scope {0} succeeded", expectedScope);
            }

            Logger.Debug("Calling custom token validator");
            var customResult = await _customValidator.ValidateAccessTokenAsync(result);

            if (customResult.IsError)
            {
                Logger.Error("Custom validator failed: " + customResult.Error ?? "unknown");
            }
            
            return customResult;
        }

        public virtual Task<TokenValidationResult> ValidateJwtAsync(string jwt, string audience = null, bool validateLifetime = true)
        {
            var handler = new JwtSecurityTokenHandler();
            handler.Configuration = new SecurityTokenHandlerConfiguration();
            handler.Configuration.CertificateValidationMode = X509CertificateValidationMode.None;
            handler.Configuration.CertificateValidator = X509CertificateValidator.None;
            
            var parameters = new TokenValidationParameters
            {
                ValidIssuer = _options.IssuerUri,
                IssuerSigningToken = new X509SecurityToken(_options.SigningCertificate),
                ValidateLifetime = validateLifetime,
            };

            if (audience.IsPresent())
            {
                parameters.ValidAudience = audience;
            }
            else
            {
                parameters.ValidateAudience = false;
            }

            try
            {
                SecurityToken jwtToken;
                var id = handler.ValidateToken(jwt, parameters, out jwtToken);
                Logger.Info("JWT access token validation successful");

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

        protected virtual async Task<TokenValidationResult> ValidateReferenceAccessTokenAsync(string tokenHandle)<commit_msg>Made token validator more flexible (still a todo for symmetric signing keys)<commit_after>﻿/*
 * Copyright 2014 <NAME>, <NAME>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Security.Claims;
using System.ServiceModel.Security;
using System.Threading.Tasks;
using Thinktecture.IdentityModel.Extensions;
using Thinktecture.IdentityServer.Core.Configuration;
using Thinktecture.IdentityServer.Core.Connect.Models;
using Thinktecture.IdentityServer.Core.Extensions;
using Thinktecture.IdentityServer.Core.Logging;
using Thinktecture.IdentityServer.Core.Services;

namespace Thinktecture.IdentityServer.Core.Connect
{
    public class TokenValidator
    {
        private readonly static ILog Logger = LogProvider.GetCurrentClassLogger();
        private readonly IdentityServerOptions _options;
        private readonly IUserService _users;
        private readonly ITokenHandleStore _tokenHandles;
        private readonly ICustomTokenValidator _customValidator;
        private readonly IClientStore _clients;

        public TokenValidator(IdentityServerOptions options, IUserService users, IClientStore clients, ITokenHandleStore tokenHandles, ICustomTokenValidator customValidator)
        {
            _options = options;
            _users = users;
            _clients = clients;
            _tokenHandles = tokenHandles;
            _customValidator = customValidator;
        }

        public virtual async Task<TokenValidationResult> ValidateIdentityTokenAsync(string token, string clientId = null, bool validateLifetime = true)
        {
            if (clientId.IsMissing())
            {
                clientId = GetClientIdFromJwt(token);

                if (clientId.IsMissing())
                {
                    return Invalid(Constants.ProtectedResourceErrors.InvalidToken);
                }
            }

            // todo: check client signing key mode
            var result = await ValidateJwtAsync(token, clientId, new X509SecurityKey(_options.SigningCertificate), validateLifetime);

            if (result.IsError)
            {
                return result;
            }

            Logger.Debug("Calling custom token validator");
            var customResult = await _customValidator.ValidateIdentityTokenAsync(result);

            if (customResult.IsError)
            {
                Logger.Error("Custom validator failed: " + customResult.Error ?? "unknown");
            }

            return customResult;
        }

        private string GetClientIdFromJwt(string token)
        {
            var jwt = new JwtSecurityToken(token);
            var clientId = jwt.Audiences.FirstOrDefault();

            return clientId;
        }

        public virtual async Task<TokenValidationResult> ValidateAccessTokenAsync(string token, string expectedScope = null)
        {
            Logger.Info("Start access token validation");
            Logger.Debug("Token: " + token);

            TokenValidationResult result;

            if (token.Contains("."))
            {
                Logger.InfoFormat("Validating a JWT access token");
                result = await ValidateJwtAsync(
                    token, 
                    string.Format(Constants.AccessTokenAudience, _options.IssuerUri),
                    new X509SecurityKey(_options.SigningCertificate));
            }
            else
            {
                Logger.InfoFormat("Validating a reference access token");
                result = await ValidateReferenceAccessTokenAsync(token);
            }

            if (result.IsError)
            {
                return result;
            }

            if (expectedScope.IsPresent())
            {
                var scope = result.Claims.FirstOrDefault(c => c.Type == Constants.ClaimTypes.Scope && c.Value == expectedScope);
                if (scope == null)
                {
                    Logger.InfoFormat("Checking for expected scope {0} failed", expectedScope);
                    return Invalid(Constants.ProtectedResourceErrors.InsufficientScope);
                }

                Logger.InfoFormat("Checking for expected scope {0} succeeded", expectedScope);
            }

            Logger.Debug("Calling custom token validator");
            var customResult = await _customValidator.ValidateAccessTokenAsync(result);

            if (customResult.IsError)
            {
                Logger.Error("Custom validator failed: " + customResult.Error ?? "unknown");
            }
            
            return customResult;
        }

        public virtual Task<TokenValidationResult> ValidateJwtAsync(string jwt, string audience, SecurityKey signingKey, bool validateLifetime = true)
        {
            var handler = new JwtSecurityTokenHandler();
            handler.Configuration = new SecurityTokenHandlerConfiguration();
            handler.Configuration.CertificateValidationMode = X509CertificateValidationMode.None;
            handler.Configuration.CertificateValidator = X509CertificateValidator.None;
            
            var parameters = new TokenValidationParameters
            {
                ValidIssuer = _options.IssuerUri,
                IssuerSigningKey = signingKey,
                ValidateLifetime = validateLifetime,
                ValidAudience = audience
            };

            try
            {
                SecurityToken jwtToken;
                var id = handler.ValidateToken(jwt, parameters, out jwtToken);
                Logger.Info("JWT access token validation successful");

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

        protected virtual async Task<TokenValidationResult> ValidateReferenceAccessTokenAsync(string tokenHandle)
{'fraction_non_alphanumeric': 0.07065301690708857, 'fraction_numerical': 0.003179773538079727, 'mean_word_length': 2.148962148962149, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5004979', 'n_tokens_mistral': 2994, 'n_tokens_neox': 2882, 'n_words': 768}