public async Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            _logger.LogDebug("Start token request validation");


            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            var raw = context.Request.Raw;

            _validatedRequest = new ValidatedTokenRequest
            {
                Raw = raw ?? throw new ArgumentNullException(nameof(raw)),
                            Options = _options
            };
            var customTokenRequestValidationContext = new CustomTokenRequestValidationContext()
            {
                Result = new TokenRequestValidationResult(_validatedRequest)
            };
            await _arbitraryResourceOwnerRequestValidator.ValidateAsync(customTokenRequestValidationContext);

            if (customTokenRequestValidationContext.Result.IsError)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest,
                                                           customTokenRequestValidationContext.Result.Error);
                return;
            }


            var clientResult = await _clientValidator.ValidateAsync(_httpContextAccessor.HttpContext);

            if (!clientResult.IsError)
            {
                _validatedRequest.SetClient(clientResult.Client);
            }

            /////////////////////////////////////////////
            // get the grant type
            // NOTE: The identityserver4 pipeline before us validated to obvious stuff
            /////////////////////////////////////////////
            var grantType = _validatedRequest.Raw.Get(OidcConstants.TokenRequest.GrantType);

            _validatedRequest.GrantType = grantType;

            var subject = "";

            if (string.IsNullOrWhiteSpace(subject))
            {
                subject = context.Request.Raw.Get("subject");
            }

            // get user's identity
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, subject),
                new Claim("sub", subject)
            };

            var principal = new ClaimsPrincipal(new ClaimsIdentity(claims));

            _principalAugmenter.AugmentPrincipal(principal);

            // optional stuff;
            var accessTokenLifetimeOverride = _validatedRequest.Raw.Get(Constants.AccessTokenLifetime);

            if (!string.IsNullOrWhiteSpace(accessTokenLifetimeOverride))
            {
                int  accessTokenLifetime = 0;
                bool error = true;
                if (Int32.TryParse(accessTokenLifetimeOverride, out accessTokenLifetime))
                {
                    if (accessTokenLifetime > 0 && accessTokenLifetime <= context.Request.AccessTokenLifetime)
                    {
                        context.Request.AccessTokenLifetime = accessTokenLifetime;
                        error = false;
                    }
                }
                if (error)
                {
                    var errorDescription =
                        $"{Constants.AccessTokenLifetime} out of range.   Must be > 0 and <= configured AccessTokenLifetime.";
                    LogError(errorDescription);
                    context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, errorDescription);
                    return;
                }
            }

            context.Result = new GrantValidationResult(principal.GetSubjectId(),
                                                       ArbitraryResourceOwnerExtensionGrant.Constants.ArbitraryResourceOwner);
        }
Esempio n. 2
0
        public async Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            _logger.LogDebug("Start token request validation");

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            var raw = context.Request.Raw;

            _validatedRequest = new ValidatedTokenRequest
            {
                Raw = raw ?? throw new ArgumentNullException(nameof(raw)),
                            Options = _options
            };
            var customTokenRequestValidationContext = new CustomTokenRequestValidationContext()
            {
                Result = new TokenRequestValidationResult(_validatedRequest)
            };
            await _arbitraryResourceOwnerRequestValidator.ValidateAsync(customTokenRequestValidationContext);

            if (customTokenRequestValidationContext.Result.IsError)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest,
                                                           customTokenRequestValidationContext.Result.Error);
                return;
            }
            var clientValidationResult = await _clientSecretValidator.ValidateAsync(_validatedRequest.Raw);

            if (clientValidationResult == null)
            {
                throw new ArgumentNullException(nameof(clientValidationResult));
            }

            _validatedRequest.SetClient(clientValidationResult.Client, clientValidationResult.Secret);

            /////////////////////////////////////////////
            // check grant type
            /////////////////////////////////////////////
            var grantType = _validatedRequest.Raw.Get(OidcConstants.TokenRequest.GrantType);

            if (grantType.IsMissing())
            {
                LogError("Grant type is missing");
                context.Result = new GrantValidationResult(TokenRequestErrors.UnsupportedGrantType);
                return;
            }
            if (grantType.Length > _options.InputLengthRestrictions.GrantType)
            {
                LogError("Grant type is too long");
                context.Result = new GrantValidationResult(TokenRequestErrors.UnsupportedGrantType);
                return;
            }

            _validatedRequest.GrantType = grantType;
            var resource = await _resourceStore.GetAllResourcesAsync();

            var   subject             = "";
            Claim originAuthTimeClaim = null;
            // if access_token exists, it wins.
            var accessToken = context.Request.Raw.Get("access_token");

            if (!string.IsNullOrWhiteSpace(accessToken))
            {
                var validateAccessToken = await _tokenValidator.ValidateAccessTokenAsync(accessToken);

                var queryClaims = from item in validateAccessToken.Claims
                                  where item.Type == JwtClaimTypes.Subject
                                  select item.Value;
                subject = queryClaims.FirstOrDefault();

                originAuthTimeClaim = (from item in validateAccessToken.Claims
                                       where item.Type == $"origin_{JwtClaimTypes.AuthenticationTime}"
                                       select item).FirstOrDefault();
                if (originAuthTimeClaim == null)
                {
                    var authTimeClaim = (from item in validateAccessToken.Claims
                                         where item.Type == JwtClaimTypes.AuthenticationTime
                                         select item).FirstOrDefault();
                    originAuthTimeClaim = new
                                          Claim($"origin_{JwtClaimTypes.AuthenticationTime}",
                                                authTimeClaim.Value);
                }
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                subject = context.Request.Raw.Get("subject");
            }
            // get user's identity
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, subject),
                new Claim("sub", subject)
            };

            var principal = new ClaimsPrincipal(new ClaimsIdentity(claims));

            _principalAugmenter.AugmentPrincipal(principal);
            var userClaimsFinal = new List <Claim>()
            {
            };


            // optional stuff;
            var accessTokenLifetimeOverride = _validatedRequest.Raw.Get(Constants.AccessTokenLifetime);

            if (!string.IsNullOrWhiteSpace(accessTokenLifetimeOverride))
            {
                var accessTokenLifetime = Int32.Parse(accessTokenLifetimeOverride);
                if (accessTokenLifetime > 0 && accessTokenLifetime < context.Request.AccessTokenLifetime)
                {
                    context.Request.AccessTokenLifetime = accessTokenLifetime;
                }
                else
                {
                    var errorDescription =
                        $"{Constants.AccessTokenLifetime} out of range.   Must be > 0 and less than configured AccessTokenLifetime.";
                    LogError(errorDescription);
                    context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, errorDescription);
                    return;
                }
            }

            //  userClaimsFinal.Add(new Claim(ProfileServiceManager.Constants.ClaimKey, Constants.ArbitraryResourceOwnerProfileService));
            if (originAuthTimeClaim != null)
            {
                userClaimsFinal.Add(originAuthTimeClaim);
            }
            context.Result = new GrantValidationResult(principal.GetSubjectId(), ArbitraryResourceOwnerExtensionGrant.Constants.ArbitraryResourceOwner, userClaimsFinal);
        }
Esempio n. 3
0
        public async Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            _logger.LogDebug("Start token request validation");

            string grantType = null;
            string clientId  = "";

            try
            {
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }
                var raw = context.Request.Raw;
                var validatedRequest = new ValidatedTokenRequest
                {
                    Raw = raw ?? throw new ArgumentNullException(nameof(raw)),
                                Options = _options
                };
                // validate HTTP for clients
                if (HttpMethods.IsPost(_httpContextAccessor.HttpContext.Request.Method) && _httpContextAccessor.HttpContext.Request.HasFormContentType)
                {
                    // validate client
                    var clientResult = await _clientValidator.ValidateAsync(_httpContextAccessor.HttpContext);

                    if (!clientResult.IsError)
                    {
                        validatedRequest.SetClient(clientResult.Client);
                        clientId = clientResult.Client.ClientId;
                    }
                }
                /////////////////////////////////////////////
                // get grant type.  This has already been validated by the time it gets here.
                /////////////////////////////////////////////
                grantType = validatedRequest.Raw.Get(OidcConstants.TokenRequest.GrantType);
                validatedRequest.GrantType = grantType;

                var customTokenRequestValidationContext = new CustomTokenRequestValidationContext()
                {
                    Result = new TokenRequestValidationResult(validatedRequest)
                };
                await _arbitraryResourceOwnerRequestValidator.ValidateAsync(customTokenRequestValidationContext);

                if (customTokenRequestValidationContext.Result.IsError)
                {
                    context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest,
                                                               customTokenRequestValidationContext.Result.Error);
                    throw new Exception("Invalid Request");
                }

                var subject = "";
                if (string.IsNullOrWhiteSpace(subject))
                {
                    subject = context.Request.Raw.Get("subject");
                }

                // get user's identity
                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, subject),
                    new Claim("sub", subject)
                };

                var principal = new ClaimsPrincipal(new ClaimsIdentity(claims));
                _principalAugmenter.AugmentPrincipal(principal);

                // optional stuff;
                var accessTokenLifetimeOverride = validatedRequest.Raw.Get(Constants.AccessTokenLifetime);
                if (!string.IsNullOrWhiteSpace(accessTokenLifetimeOverride))
                {
                    var accessTokenLifetime = Int32.Parse(accessTokenLifetimeOverride);
                    if (accessTokenLifetime > 0 && accessTokenLifetime <= context.Request.AccessTokenLifetime)
                    {
                        context.Request.AccessTokenLifetime = accessTokenLifetime;
                    }
                    else
                    {
                        var errorDescription =
                            $"{Constants.AccessTokenLifetime} out of range.   Must be > 0 and <= configured AccessTokenLifetime.";
                        LogError(errorDescription);
                        context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, errorDescription);
                        throw new Exception(errorDescription);
                    }
                }

                context.Result = new GrantValidationResult(principal.GetSubjectId(),
                                                           ArbitraryResourceOwnerExtensionGrant.Constants.ArbitraryResourceOwner);
            }
            catch (Exception e)
            {
            }

            if (context.Result.IsError)
            {
                await _events.RaiseAsync(new ExtensionGrantValidationFailureEvent(
                                             clientId,
                                             grantType,
                                             context.Result.Error));
            }
        }