/// <summary>
        /// Creates the response for a refresh token request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        protected virtual async Task <TokenResponse> ProcessRefreshTokenRequestAsync(TokenRequestValidationResult request)
        {
            Logger.LogTrace("Creating response for refresh token request");

            var    oldAccessToken = request.ValidatedRequest.RefreshToken.AccessToken;
            string accessTokenString;

            if (request.ValidatedRequest.Client.UpdateAccessTokenClaimsOnRefresh)
            {
                var subject = request.ValidatedRequest.RefreshToken.Subject;

                var parsedScopes = await ResourceValidator.ParseRequestedScopesAsync(oldAccessToken.Scopes);

                var validatedResources = await Resources.CreateResourceValidationResult(parsedScopes);

                var creationRequest = new TokenCreationRequest
                {
                    Subject            = subject,
                    Description        = request.ValidatedRequest.RefreshToken.Description,
                    ValidatedRequest   = request.ValidatedRequest,
                    ValidatedResources = validatedResources
                };

                var newAccessToken = await TokenService.CreateAccessTokenAsync(creationRequest);

                accessTokenString = await TokenService.CreateSecurityTokenAsync(newAccessToken);
            }
            else
            {
                oldAccessToken.CreationTime = Clock.UtcNow.UtcDateTime;
                oldAccessToken.Lifetime     = request.ValidatedRequest.AccessTokenLifetime;

                accessTokenString = await TokenService.CreateSecurityTokenAsync(oldAccessToken);
            }

            var handle = await RefreshTokenService.UpdateRefreshTokenAsync(request.ValidatedRequest.RefreshTokenHandle, request.ValidatedRequest.RefreshToken, request.ValidatedRequest.Client);

            return(new TokenResponse
            {
                IdentityToken = await CreateIdTokenFromRefreshTokenRequestAsync(request.ValidatedRequest, accessTokenString),
                AccessToken = accessTokenString,
                AccessTokenLifetime = request.ValidatedRequest.AccessTokenLifetime,
                RefreshToken = handle,
                Custom = request.CustomResponse,
                Scope = request.ValidatedRequest.RefreshToken.Scopes.ToSpaceSeparatedString()
            });
        }
Esempio n. 2
0
        private TokenRequestValidationResult ValidatePopParameters(NameValueCollection parameters)
        {
            var invalid = new TokenRequestValidationResult
            {
                IsError = true,
                Error   = Constants.TokenErrors.InvalidRequest
            };

            // check optional alg
            var alg = parameters.Get(Constants.TokenRequest.Algorithm);

            if (alg != null)
            {
                // for now we only support asymmetric
                if (!Constants.AllowedProofKeyAlgorithms.Contains(alg))
                {
                    invalid.ErrorDescription = "invalid alg.";
                    return(invalid);
                }

                _validatedRequest.ProofKeyAlgorithm = alg;
            }

            // key is required - for now we only support client generated keys
            var key = parameters.Get(Constants.TokenRequest.Key);

            if (key == null)
            {
                invalid.ErrorDescription = "key is required.";
                return(invalid);
            }
            if (key.Length > _options.InputLengthRestrictions.ProofKey)
            {
                invalid.ErrorDescription = "invalid key.";
                Logger.Warn("Proof key exceeds max allowed length.");
                return(invalid);
            }

            var jwk = string.Format("{{ \"jwk\":{0} }}", Encoding.UTF8.GetString(Base64Url.Decode(key)));

            _validatedRequest.ProofKey = jwk;

            return(new TokenRequestValidationResult {
                IsError = false
            });
        }
Esempio n. 3
0
        private void LogTokens(TokenResponse response, TokenRequestValidationResult requestResult)
        {
            var clientId  = $"{requestResult.ValidatedRequest.Client.ClientId} ({requestResult.ValidatedRequest.Client?.ClientName ?? "no name set"})";
            var subjectId = requestResult.ValidatedRequest.Subject?.GetSubjectId() ?? "no subject";

            if (response.IdentityToken != null)
            {
                _logger.LogTrace("Identity token issued for {clientId} / {subjectId}: {token}", clientId, subjectId, response.IdentityToken);
            }
            if (response.RefreshToken != null)
            {
                _logger.LogTrace("Refresh token issued for {clientId} / {subjectId}: {token}", clientId, subjectId, response.RefreshToken);
            }
            if (response.AccessToken != null)
            {
                _logger.LogTrace("Access token issued for {clientId} / {subjectId}: {token}", clientId, subjectId, response.AccessToken);
            }
        }
        /// <summary>
        /// Creates the response for a token request.
        /// </summary>
        /// <param name="validationResult">The validation result.</param>
        /// <returns></returns>
        protected virtual async Task <TokenResponse> ProcessTokenRequestAsync(TokenRequestValidationResult validationResult)
        {
            (var accessToken, var refreshToken) = await CreateAccessTokenAsync(validationResult.ValidatedRequest);

            var response = new TokenResponse
            {
                AccessToken         = accessToken,
                AccessTokenLifetime = validationResult.ValidatedRequest.AccessTokenLifetime,
                Custom = validationResult.CustomResponse
            };

            if (refreshToken.IsPresent())
            {
                response.RefreshToken = refreshToken;
            }

            return(response);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TokenIssuedSuccessEvent"/> class.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="request">The request.</param>
        public TokenIssuedSuccessEvent(TokenResponse response, TokenRequestValidationResult request)
            : this()
        {
            ClientId   = request.ValidatedRequest.Client.ClientId;
            ClientName = request.ValidatedRequest.Client.ClientName;
            Endpoint   = EndpointName.Token.ToString();
            GrantType  = request.ValidatedRequest.GrantType;

            if (GrantType == OidcConstants.GrantTypes.RefreshToken)
            {
                SubjectId    = request.ValidatedRequest.RefreshToken.Subject?.GetSubjectId();
                SubjectEmail = request.ValidatedRequest.RefreshToken.Subject?.Claims?.FirstOrDefault(claim => claim.Type == ClaimTypes.Email)?.Value;
                Scopes       = request.ValidatedRequest.RefreshToken.AccessToken.Scopes.ToSpaceSeparatedString();
            }
            else if (GrantType == OidcConstants.GrantTypes.AuthorizationCode)
            {
                SubjectId    = request.ValidatedRequest.AuthorizationCode.Subject?.GetSubjectId();
                SubjectEmail = request.ValidatedRequest.AuthorizationCode.Subject?.Claims?.FirstOrDefault(claim => claim.Type == ClaimTypes.Email)?.Value;
                Scopes       = request.ValidatedRequest.AuthorizationCode.RequestedScopes.ToSpaceSeparatedString();
            }
            else
            {
                SubjectId    = request.ValidatedRequest.Subject?.GetSubjectId();
                SubjectEmail = request.ValidatedRequest.Subject?.Claims?.FirstOrDefault(claim => claim.Type == ClaimTypes.Email)?.Value;
                Scopes       = request.ValidatedRequest.ValidatedScopes?.GrantedResources.ToScopeNames().ToSpaceSeparatedString();
            }

            var tokens = new List <Token>();

            if (response.IdentityToken != null)
            {
                tokens.Add(new Token(OidcConstants.TokenTypes.IdentityToken, response.IdentityToken));
            }
            if (response.RefreshToken != null)
            {
                tokens.Add(new Token(OidcConstants.TokenTypes.RefreshToken, response.RefreshToken));
            }
            if (response.AccessToken != null)
            {
                tokens.Add(new Token(OidcConstants.TokenTypes.AccessToken, response.AccessToken));
            }
            Tokens = tokens;
        }
Esempio n. 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TokenIssuedFailureEvent"/> class.
        /// </summary>
        /// <param name="result">The result.</param>
        public TokenIssuedFailureEvent(TokenRequestValidationResult result)
            : this()
        {
            if (result.ValidatedRequest != null)
            {
                ClientId   = result.ValidatedRequest.Client.ClientId;
                ClientName = result.ValidatedRequest.Client.ClientName;
                GrantType  = result.ValidatedRequest.GrantType;
                Scopes     = result.ValidatedRequest.Scopes?.ToSpaceSeparatedString();

                if (result.ValidatedRequest.Subject != null && result.ValidatedRequest.Subject.Identity.IsAuthenticated)
                {
                    SubjectId = result.ValidatedRequest.Subject.GetSubjectId();
                }
            }

            Endpoint         = EndpointNames.Token;
            Error            = result.Error;
            ErrorDescription = result.ErrorDescription;
        }
Esempio n. 7
0
 public void InitialData()
 {
     this.clientValidator = new ClientCredentialsRequestValidator(this.authConfiguration);
     this.client          = new Client {
         ClientId = "1"
     };
     this.validatedTokenRequestWithNullRaw = new ValidatedTokenRequest {
         Client = this.client,
         Raw    = null
     };
     this.validatedTokenRequestWithRaw = new ValidatedTokenRequest {
         Client = this.client,
         Raw    = new NameValueCollection()
     };
     this.invalidEmailResult                      = new TokenRequestValidationResult(null, "invalid_email");
     this.clientValidationErrorResult             = new TokenRequestValidationResult(null, "client_validation_error");
     this.tokenRequestValidationResultWithNullRaw = new TokenRequestValidationResult(this.validatedTokenRequestWithNullRaw);
     this.tokenRequestValidationResultRaw         = new TokenRequestValidationResult(this.validatedTokenRequestWithRaw);
     this.claim = new Claim("email", "*****@*****.**");
 }
        /// <summary>
        /// Processes the response.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public virtual async Task <TokenResponse> ProcessAsync(TokenRequestValidationResult request)
        {
            switch (request.ValidatedRequest.GrantType)
            {
            case OidcConstants.GrantTypes.ClientCredentials:
                return(await ProcessClientCredentialsRequestAsync(request));

            case OidcConstants.GrantTypes.Password:
                return(await ProcessPasswordRequestAsync(request));

            case OidcConstants.GrantTypes.AuthorizationCode:
                return(await ProcessAuthorizationCodeRequestAsync(request));

            case OidcConstants.GrantTypes.RefreshToken:
                return(await ProcessRefreshTokenRequestAsync(request));

            default:
                return(await ProcessExtensionGrantRequestAsync(request));
            }
        }
Esempio n. 9
0
        private async Task <TokenResponse> ProcessTokenRequestAsync(TokenRequestValidationResult validationResult)
        {
            _logger.LogTrace("Processing token request");

            var accessToken = await CreateAccessTokenAsync(validationResult.ValidatedRequest);

            var response = new TokenResponse
            {
                AccessToken         = accessToken.Item1,
                AccessTokenLifetime = validationResult.ValidatedRequest.Client.AccessTokenLifetime,
                Custom = validationResult.CustomResponse
            };

            if (accessToken.Item2.IsPresent())
            {
                response.RefreshToken = accessToken.Item2;
            }

            return(response);
        }
        public override Task <TokenResponse> ProcessAsync(TokenRequestValidationResult request)
        {
            string clientId = request.ValidatedRequest.Client.ClientId;
            string launchId = request.ValidatedRequest.Raw.Get("launch");

            if (!string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(launchId))
            {
                LaunchContext launchContext = Config.GetLaunchContext(launchId, clientId);
                if (launchContext != null)
                {
                    request.CustomResponse = new Dictionary <string, object>
                    {
                        { "patient", launchContext.Patient },
                        { "practitioner", launchContext.Practitioner },
                        { "encounter", launchContext.Encounter }
                    };
                }
            }

            return(base.ProcessAsync(request));
        }
        /// <summary>
        /// Creates the response for a refresh token request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        private async Task <TokenResponse> ProcessRefreshTokenRequestAsync(TokenRequestValidationResult request)
        {
            Logger.LogTrace("Creating response for refresh token request");

            var    oldAccessToken = request.ValidatedRequest.RefreshToken.AccessToken;
            string accessTokenString;

            if (request.ValidatedRequest.Client.UpdateAccessTokenClaimsOnRefresh)
            {
                var subject = request.ValidatedRequest.RefreshToken.Subject;

                var creationRequest = new TokenCreationRequest
                {
                    Subject          = subject,
                    ValidatedRequest = request.ValidatedRequest,
                    Resources        = await Resources.FindEnabledResourcesByScopeAsync(oldAccessToken.Scopes)
                };

                var newAccessToken = await TokenService.CreateAccessTokenAsync(creationRequest);

                accessTokenString = await TokenService.CreateSecurityTokenAsync(newAccessToken);
            }
            else
            {
                oldAccessToken.CreationTime = IdentityServerDateTime.UtcNow;
                oldAccessToken.Lifetime     = request.ValidatedRequest.AccessTokenLifetime;

                accessTokenString = await TokenService.CreateSecurityTokenAsync(oldAccessToken);
            }

            var handle = await RefreshTokenService.UpdateRefreshTokenAsync(request.ValidatedRequest.RefreshTokenHandle, request.ValidatedRequest.RefreshToken, request.ValidatedRequest.Client);

            return(new TokenResponse
            {
                IdentityToken = await CreateIdTokenFromRefreshTokenRequestAsync(request.ValidatedRequest, accessTokenString),
                AccessToken = accessTokenString,
                AccessTokenLifetime = request.ValidatedRequest.AccessTokenLifetime,
                RefreshToken = handle
            });
        }
Esempio n. 12
0
        public override async Task <TokenResponse> ProcessAsync(TokenRequestValidationResult request)
        {
            var result = new TokenResponse();

            switch (request.ValidatedRequest.GrantType)
            {
            case OidcConstants.GrantTypes.ClientCredentials:
                result = await ProcessClientCredentialsRequestAsync(request);

                break;

            case OidcConstants.GrantTypes.Password:
                result = await ProcessPasswordRequestAsync(request);

                break;

            case OidcConstants.GrantTypes.AuthorizationCode:
                result = await ProcessAuthorizationCodeRequestAsync(request);

                break;

            case OidcConstants.GrantTypes.RefreshToken:
                result = await ProcessRefreshTokenRequestAsync(request);

                break;

            default:
                result = await ProcessExtensionGrantRequestAsync(request);

                break;
            }
            //if (result != null)
            //{
            //    result.Custom = new Dictionary<string, object> { };
            //    result.Custom.Add("Code", 1);
            //}

            return(result);
        }
Esempio n. 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public override async Task <TokenResponse> ProcessAsync(TokenRequestValidationResult request)
        {
            var result = new TokenResponse();

            switch (request.ValidatedRequest.GrantType)
            {
            case OidcConstants.GrantTypes.ClientCredentials:
                result = await ProcessClientCredentialsRequestAsync(request);

                break;

            case OidcConstants.GrantTypes.Password:
                result = await ProcessPasswordRequestAsync(request);

                break;

            case OidcConstants.GrantTypes.AuthorizationCode:
                result = await ProcessAuthorizationCodeRequestAsync(request);

                break;

            case OidcConstants.GrantTypes.RefreshToken:
                result = await ProcessRefreshTokenRequestAsync(request);

                break;

            default:
                result = await ProcessExtensionGrantRequestAsync(request);

                break;
            }
            var resultText = JsonConvert.SerializeObject(result);
            var key        = request.ValidatedRequest.Subject.GetSubjectId().GetKey();

            Logger.LogInformation($"白名单key写入:{key}");
            await _cache.SetStringAsync(key, resultText);

            return(result);
        }
Esempio n. 14
0
    /// <summary>
    /// Initializes a new instance of the <see cref="TokenIssuedSuccessEvent"/> class.
    /// </summary>
    /// <param name="response">The response.</param>
    /// <param name="request">The request.</param>
    public TokenIssuedSuccessEvent(TokenResponse response, TokenRequestValidationResult request)
        : this()
    {
        ClientId   = request.ValidatedRequest.Client.ClientId;
        ClientName = request.ValidatedRequest.Client.ClientName;
        Endpoint   = Constants.EndpointNames.Token;
        SubjectId  = request.ValidatedRequest.Subject?.GetSubjectId();
        GrantType  = request.ValidatedRequest.GrantType;

        if (GrantType == OidcConstants.GrantTypes.RefreshToken)
        {
            Scopes = request.ValidatedRequest.RefreshToken.AuthorizedScopes.ToSpaceSeparatedString();
        }
        else if (GrantType == OidcConstants.GrantTypes.AuthorizationCode)
        {
            Scopes = request.ValidatedRequest.AuthorizationCode.RequestedScopes.ToSpaceSeparatedString();
        }
        else
        {
            Scopes = request.ValidatedRequest.ValidatedResources?.RawScopeValues.ToSpaceSeparatedString();
        }

        var tokens = new List <Token>();

        if (response.IdentityToken != null)
        {
            tokens.Add(new Token(OidcConstants.TokenTypes.IdentityToken, response.IdentityToken));
        }
        if (response.RefreshToken != null)
        {
            tokens.Add(new Token(OidcConstants.TokenTypes.RefreshToken, response.RefreshToken));
        }
        if (response.AccessToken != null)
        {
            tokens.Add(new Token(OidcConstants.TokenTypes.AccessToken, response.AccessToken));
        }
        Tokens = tokens;
    }
Esempio n. 15
0
        protected override async Task <TokenResponse> ProcessTokenRequestAsync(TokenRequestValidationResult validationResult)
        {
            switch (validationResult.ValidatedRequest.GrantType)
            {
            case FluffyBunny4.Constants.GrantType.ArbitraryToken:
                return(await ProcessArbitraryTokenTokenResponse(validationResult));

                break;

            case FluffyBunny4.Constants.GrantType.ArbitraryIdentity:
                return(await ProcessArbitraryIdentityTokenResponse(validationResult));

                break;

            default:
                var response = await base.ProcessTokenRequestAsync(validationResult);

//                    response.Scope = validationResult.ValidatedRequest.RequestedScopes.ToSpaceSeparatedString();
                return(response);

                break;
            }
        }
Esempio n. 16
0
        protected override async Task <TokenResponse> ProcessRefreshTokenRequestAsync(TokenRequestValidationResult request)
        {
            var response = await base.ProcessRefreshTokenRequestAsync(request);

            var refreshTokenExtra = request.ValidatedRequest.RefreshToken as RefreshTokenExtra;

            switch (refreshTokenExtra.OriginGrantType)
            {
            case FluffyBunny4.Constants.GrantType.ArbitraryIdentity:
            case FluffyBunny4.Constants.GrantType.ArbitraryToken:
            case OidcConstants.GrantTypes.DeviceCode:
            case FluffyBunny4.Constants.GrantType.TokenExchange:
            case FluffyBunny4.Constants.GrantType.TokenExchangeMutate:
                response.RefreshToken = $"1_{response.RefreshToken}";
                if (!string.IsNullOrWhiteSpace(response.AccessToken) && !response.AccessToken.Contains("."))
                {
                    response.AccessToken = $"1_{response.AccessToken}";
                }

                break;

            default:
                response.RefreshToken = $"0_{response.RefreshToken}";
                if (!string.IsNullOrWhiteSpace(response.AccessToken) && !response.AccessToken.Contains("."))
                {
                    response.AccessToken = $"0_{response.AccessToken}";
                }

                break;
            }

            return(response);
        }
        private TokenRequestValidationResult Invalid(string error, string errorDescription = "")
        {
            var result = new TokenRequestValidationResult
            {
                IsError = true,
                Error = error
            };

            if (errorDescription.IsPresent())
            {
                result.ErrorDescription = errorDescription;
            }

            return result;
        }
Esempio n. 18
0
        private async Task <TokenResponse> ProcessArbitraryIdentityTokenResponse(TokenRequestValidationResult validationResult)
        {
            var form    = validationResult.ValidatedRequest.Raw;
            var subject =
                validationResult.ValidatedRequest.Subject.Claims.FirstOrDefault(x =>
                                                                                x.Type == JwtClaimTypes.Subject);
            var resultClaims = new List <Claim>
            {
                subject,
                new Claim(JwtClaimTypes.AuthenticationTime, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(),
                          ClaimValueTypes.Integer64),
            };
            var accessTokenResultClaims = new List <Claim>(resultClaims);

            resultClaims.AddRange(_scopedOptionalClaims.Claims);
            accessTokenResultClaims.AddRange(_scopedOptionalClaims.ArbitraryIdentityAccessTokenClaims);

            var issuer = validationResult.ValidatedRequest.Raw.Get("issuer");

            if (string.IsNullOrEmpty(issuer))
            {
                issuer = _contextAccessor.HttpContext.GetIdentityServerIssuerUri();
            }

            var atClaims = accessTokenResultClaims.Distinct(new ClaimComparer()).ToList();

            var tokenLifetimeOverride = form.Get(Constants.AccessTokenLifetime);
            int accessTokenLifetime   = validationResult.ValidatedRequest.Client.AccessTokenLifetime;

            if (!string.IsNullOrWhiteSpace(tokenLifetimeOverride))
            {
                int.TryParse(tokenLifetimeOverride, out accessTokenLifetime);
            }
            tokenLifetimeOverride = form.Get(Constants.IdTokenLifetime);
            int identityTokenLifetime = validationResult.ValidatedRequest.Client.IdentityTokenLifetime;

            if (!string.IsNullOrWhiteSpace(tokenLifetimeOverride))
            {
                int.TryParse(tokenLifetimeOverride, out identityTokenLifetime);
            }

            var at = new Token(OidcConstants.TokenTypes.AccessToken)
            {
                CreationTime = Clock.UtcNow.UtcDateTime,
                Issuer       = issuer,
                Lifetime     = accessTokenLifetime,
                Claims       = atClaims,
                ClientId     = validationResult.ValidatedRequest.ClientId,
                //    Description = request.Description,
                AccessTokenType          = validationResult.ValidatedRequest.AccessTokenType,
                AllowedSigningAlgorithms = validationResult.ValidatedRequest.Client.AllowedIdentityTokenSigningAlgorithms,
            };

            //  var at = await TokenService.CreateAccessTokenAsync(tokenRequest);
            var accessToken = await TokenService.CreateSecurityTokenAsync(at);


            var idToken = new Token(OidcConstants.TokenTypes.IdentityToken)
            {
                CreationTime = Clock.UtcNow.UtcDateTime,
                //  Audiences = { aud },
                Issuer                   = issuer,
                Lifetime                 = identityTokenLifetime,
                Claims                   = resultClaims.Distinct(new ClaimComparer()).ToList(),
                ClientId                 = validationResult.ValidatedRequest.ClientId,
                AccessTokenType          = validationResult.ValidatedRequest.AccessTokenType,
                AllowedSigningAlgorithms = validationResult.ValidatedRequest.Client.AllowedIdentityTokenSigningAlgorithms
            };
            var jwtIdToken = await TokenService.CreateSecurityTokenAsync(idToken);

            var tokenResonse = new TokenResponse
            {
                AccessToken         = accessToken,
                IdentityToken       = jwtIdToken,
                AccessTokenLifetime = accessTokenLifetime
            };

            return(tokenResonse);
        }
Esempio n. 19
0
        protected virtual async Task <TokenResponse> ProcessAuthorizationCodeRequestAsync(TokenRequestValidationResult request)
        {
            //Logger.LogTrace("Creating response for authorization code request");

            //////////////////////////
            // access token
            /////////////////////////
            (var accessToken, var refreshToken) = await CreateAccessTokenAsync(request.ValidatedRequest);

            var response = new TokenResponse
            {
                AccessToken         = accessToken,
                AccessTokenLifetime = request.ValidatedRequest.AccessTokenLifetime,
                Custom       = request.CustomResponse,
                Scope        = string.Join(" ", request.ValidatedRequest.AuthorizationCode.RequestedScopes),
                RefreshToken = refreshToken
            };

            return(response);
        }
Esempio n. 20
0
        private async Task <TokenResponse> ProcessArbitraryTokenTokenResponse(TokenRequestValidationResult validationResult)
        {
            var subject =
                validationResult.ValidatedRequest.Subject.Claims.FirstOrDefault(x =>
                                                                                x.Type == JwtClaimTypes.Subject);


            var form         = validationResult.ValidatedRequest.Raw;
            var resultClaims = new List <Claim>()
            {
                subject
            };

            resultClaims.AddRange(_scopedOptionalClaims.Claims);
            var issuer = validationResult.ValidatedRequest.Raw.Get("issuer");

            if (string.IsNullOrEmpty(issuer))
            {
                issuer = _contextAccessor.HttpContext.GetIdentityServerIssuerUri();
            }

            var atClaims = resultClaims.Distinct(new ClaimComparer()).ToList();

            bool createRefreshToken;

            var offlineAccessClaim =
                atClaims.FirstOrDefault(x =>
                                        x.Type == JwtClaimTypes.Scope && x.Value == IdentityServerConstants.StandardScopes.OfflineAccess);

            createRefreshToken = offlineAccessClaim != null;

            var authorizedScopes = (from c in atClaims
                                    where c.Type == JwtClaimTypes.Scope
                                    select c.Value).ToList();

            var accessTokenLifetimeOverride = form.Get(Constants.AccessTokenLifetime);

            int accessTokenLifetime = validationResult.ValidatedRequest.AccessTokenLifetime;

            if (!string.IsNullOrWhiteSpace(accessTokenLifetimeOverride))
            {
                int.TryParse(accessTokenLifetimeOverride, out accessTokenLifetime);
            }



            var at = new Token(OidcConstants.TokenTypes.AccessToken)
            {
                CreationTime = Clock.UtcNow.UtcDateTime,
                Issuer       = issuer,
                Lifetime     = accessTokenLifetime,
                Claims       = atClaims,
                ClientId     = validationResult.ValidatedRequest.ClientId,
                //    Description = request.Description,
                AccessTokenType          = validationResult.ValidatedRequest.AccessTokenType,
                AllowedSigningAlgorithms = validationResult.ValidatedRequest.Client.AllowedIdentityTokenSigningAlgorithms,
            };
            var accessToken = await TokenService.CreateSecurityTokenAsync(at);

            string refreshToken = null;

            if (createRefreshToken)
            {
                var refreshTokenCreationRequest = new RefreshTokenCreationRequest
                {
                    Subject          = validationResult.ValidatedRequest.Subject,
                    AccessToken      = at,
                    Client           = validationResult.ValidatedRequest.Client,
                    AuthorizedScopes = authorizedScopes
                };
                refreshToken = await RefreshTokenService.CreateRefreshTokenAsync(refreshTokenCreationRequest);
            }

            var tokenResonse = new TokenResponse
            {
                AccessToken         = accessToken,
                IdentityToken       = null,
                RefreshToken        = $"1_{refreshToken}",
                AccessTokenLifetime = accessTokenLifetime
            };

            return(tokenResonse);
        }
        public async Task <TokenResponse> ProcessAsync(ITokenResponseGeneratorHookHost host,
                                                       TokenRequestValidationResult request)
        {
            var grantType = request.ValidatedRequest.GrantType;

            if (grantType != Constants.ArbitraryIdentity)
            {
                return(null);
            }

            Logger.LogTrace($"Creating response for {Constants.ArbitraryIdentity} request");
            var subject = request.ValidatedRequest.Subject;

            //////////////////////////
            // access token
            /////////////////////////
            (var accessToken, var refreshToken) = await host.CreateAccessTokenAsync(request.ValidatedRequest);

            var response = new TokenResponse
            {
                AccessToken         = accessToken,
                AccessTokenLifetime = request.ValidatedRequest.AccessTokenLifetime,
                Custom = request.CustomResponse
            };

            //////////////////////////
            // refresh token
            /////////////////////////
            if (refreshToken.IsPresent())
            {
                response.RefreshToken = refreshToken;
            }

            // load the client that belongs to the authorization code
            Client client = null;

            if (request.ValidatedRequest.Client.ClientId != null)
            {
                client = await Clients.FindEnabledClientByIdAsync(request.ValidatedRequest.Client.ClientId);
            }

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

            // var resources = await Resources.FindEnabledResourcesByScopeAsync(request.ValidatedRequest.AuthorizationCode.RequestedScopes);

            var tokenRequest = new TokenCreationRequest
            {
                Subject                  = subject,
                Resources                = request.ValidatedRequest.ValidatedScopes.RequestedResources,
                Nonce                    = null,
                AccessTokenToHash        = response.AccessToken,
                ValidatedRequest         = request.ValidatedRequest,
                IncludeAllIdentityClaims = true
            };

            var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest);

            var jwt = await TokenService.CreateSecurityTokenAsync(idToken);

            response.IdentityToken = jwt;
            return(response);
        }
Esempio n. 22
0
        /// <summary>
        /// Creates the response for an client credentials request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        protected virtual Task <TokenResponse> ProcessClientCredentialsRequestAsync(TokenRequestValidationResult request)
        {
            Logger.LogTrace("Creating response for client credentials request");

            return(ProcessTokenRequestAsync(request));
        }
        /// <summary>
        /// Creates the response for an authorization code request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">Client does not exist anymore.</exception>
        protected virtual async Task <TokenResponse> ProcessAuthorizationCodeRequestAsync(TokenRequestValidationResult request)
        {
            Logger.LogTrace("Creating response for authorization code request");

            //////////////////////////
            // access token
            /////////////////////////
            (var accessToken, var refreshToken) = await CreateAccessTokenAsync(request.ValidatedRequest);

            var response = new TokenResponse
            {
                AccessToken         = accessToken,
                AccessTokenLifetime = request.ValidatedRequest.AccessTokenLifetime
            };

            //////////////////////////
            // refresh token
            /////////////////////////
            if (refreshToken.IsPresent())
            {
                response.RefreshToken = refreshToken;
            }

            //////////////////////////
            // id token
            /////////////////////////
            if (request.ValidatedRequest.AuthorizationCode.IsOpenId)
            {
                // load the client that belongs to the authorization code
                Client client = null;
                if (request.ValidatedRequest.AuthorizationCode.ClientId != null)
                {
                    client = await Clients.FindEnabledClientByIdAsync(request.ValidatedRequest.AuthorizationCode.ClientId);
                }
                if (client == null)
                {
                    throw new InvalidOperationException("Client does not exist anymore.");
                }

                var resources = await Resources.FindEnabledResourcesByScopeAsync(request.ValidatedRequest.AuthorizationCode.RequestedScopes);

                var tokenRequest = new TokenCreationRequest
                {
                    Subject           = request.ValidatedRequest.AuthorizationCode.Subject,
                    Resources         = resources,
                    Nonce             = request.ValidatedRequest.AuthorizationCode.Nonce,
                    AccessTokenToHash = response.AccessToken,
                    ValidatedRequest  = request.ValidatedRequest
                };

                var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest);

                var jwt = await TokenService.CreateSecurityTokenAsync(idToken);

                response.IdentityToken = jwt;
            }

            return(response);
        }
 public Task <TokenResponse> ProcessAsync(TokenRequestValidationResult validationResult)
 {
     throw new NotImplementedException();
 }
Esempio n. 25
0
        public override async Task <TokenResponse> ProcessAsync(TokenRequestValidationResult request)
        {
            var result = await base.ProcessAsync(request);

            return(result);
        }
Esempio n. 26
0
        /// <summary>
        /// Processes the response for device code grant request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        protected virtual async Task <TokenResponse> ProcessDeviceCodeRequestAsync(TokenRequestValidationResult request)
        {
            Logger.LogTrace("Creating response for device code request");

            //////////////////////////
            // access token
            /////////////////////////
            var(accessToken, refreshToken) = await CreateAccessTokenAsync(request.ValidatedRequest);

            var response = new TokenResponse
            {
                AccessToken         = accessToken,
                AccessTokenLifetime = request.ValidatedRequest.AccessTokenLifetime,
                Custom = request.CustomResponse,
                Scope  = request.ValidatedRequest.DeviceCode.AuthorizedScopes.ToSpaceSeparatedString()
            };

            //////////////////////////
            // refresh token
            /////////////////////////
            if (refreshToken.IsPresent())
            {
                response.RefreshToken = refreshToken;
            }

            //////////////////////////
            // id token
            /////////////////////////
            if (request.ValidatedRequest.DeviceCode.IsOpenId)
            {
                // load the client that belongs to the device code
                Client client = null;
                if (request.ValidatedRequest.DeviceCode.ClientId != null)
                {
                    client = await Clients.FindEnabledClientByIdAsync(request.ValidatedRequest.DeviceCode.ClientId);
                }
                if (client == null)
                {
                    throw new InvalidOperationException("Client does not exist anymore.");
                }

                var parsedScopes = await ResourceValidator.ParseRequestedScopesAsync(request.ValidatedRequest.DeviceCode.AuthorizedScopes);

                var validatedResources = await Resources.CreateResourceValidationResult(parsedScopes);

                var tokenRequest = new TokenCreationRequest
                {
                    Subject            = request.ValidatedRequest.DeviceCode.Subject,
                    ValidatedResources = validatedResources,
                    AccessTokenToHash  = response.AccessToken,
                    ValidatedRequest   = request.ValidatedRequest
                };

                var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest);

                var jwt = await TokenService.CreateSecurityTokenAsync(idToken);

                response.IdentityToken = jwt;
            }

            return(response);
        }
Esempio n. 27
0
        /// <summary>
        /// Creates the response for a password request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        protected virtual Task <TokenResponse> ProcessPasswordRequestAsync(TokenRequestValidationResult request)
        {
            Logger.LogTrace("Creating response for password request");

            return(ProcessTokenRequestAsync(request));
        }
        private TokenRequestValidationResult ValidatePopParameters(NameValueCollection parameters)
        {
            var invalid = new TokenRequestValidationResult
            {
                IsError = true,
                Error = Constants.TokenErrors.InvalidRequest
            };

            // check optional alg
            var alg = parameters.Get(Constants.TokenRequest.Algorithm);
            if (alg != null)
            {
                // for now we only support asymmetric
                if (!Constants.AllowedProofKeyAlgorithms.Contains(alg))
                {
                    invalid.ErrorDescription = "invalid alg.";
                    return invalid;
                }

                _validatedRequest.ProofKeyAlgorithm = alg;
            }
            
            // key is required - for now we only support client generated keys
            var key = parameters.Get(Constants.TokenRequest.Key);
            if (key == null)
            {
                invalid.ErrorDescription = "key is required.";
                return invalid;
            }
            if (key.Length > _options.InputLengthRestrictions.ProofKey)
            {
                invalid.ErrorDescription = "invalid key.";
                Logger.Warn("Proof key exceeds max allowed length.");
                return invalid;
            }

            var jwk = string.Format("{{ \"jwk\":{0} }}", Encoding.UTF8.GetString(Base64Url.Decode(key)));
            _validatedRequest.ProofKey = jwk;

            return new TokenRequestValidationResult { IsError = false };
        }
Esempio n. 29
0
        /// <summary>
        /// Creates the response for an extension grant request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        protected virtual Task <TokenResponse> ProcessExtensionGrantRequestAsync(TokenRequestValidationResult request)
        {
            Logger.LogTrace("Creating response for extension grant request");

            return(ProcessTokenRequestAsync(request));
        }
 /// <summary>
 /// Processes the response.
 /// </summary>
 /// <param name="request">The request.</param>
 /// <returns></returns>
 public virtual async Task <TokenResponse> ProcessAsync(TokenRequestValidationResult request) =>
 request.ValidatedRequest.GrantType switch
 {