private async Task <IEndpointResult> ProcessTokenRequestAsync(HttpContext context)
        {
            _logger.LogDebug("Start token request.");

            // validate client
            var clientResult = await _clientValidator.ValidateAsync(context);

            if (clientResult.Client == null)
            {
                return(Error(OidcConstants.TokenErrors.InvalidClient));
            }

            // validate request
            var requestResult = await _requestValidator.ValidateRequestAsync(
                (await context.Request.ReadFormAsync()).AsNameValueCollection(),
                clientResult.Client);

            if (requestResult.IsError)
            {
                return(Error(requestResult.Error, requestResult.ErrorDescription, requestResult.CustomResponse));
            }

            // create response
            var response = await _responseGenerator.ProcessAsync(requestResult);

            // return result
            _logger.LogDebug("Token request success.");
            return(new TokenResult(response));
        }
Exemple #2
0
        private async Task <IdpTokenResponse> GetIdpToken(NameValueCollection parameters)
        {
            var clientResult = await _clientValidator.ValidateAsync(_httpContextAccessor.HttpContext);

            if (clientResult.IsError)
            {
                return(new IdpTokenResponse {
                    Custom = new Dictionary <string, object> {
                        { "Error", "invalid_client" }, { "ErrorDescription", "Invalid client/secret combination" }
                    }
                });
            }

            var validationResult = await _requestValidator.ValidateRequestAsync(parameters, clientResult);

            if (validationResult.IsError)
            {
                return(new IdpTokenResponse {
                    Custom = new Dictionary <string, object> {
                        { "Error", validationResult.Error }, { "ErrorDescription", validationResult.ErrorDescription }
                    }
                });
            }

            return(await _responseGenerator.ProcessAsync(validationResult));
        }
        public async Task <IEndpointResult> ProcessAsync(IdentityServerContext context)
        {
            _logger.LogTrace("Start token request.");

            // validate HTTP
            if (context.HttpContext.Request.Method != "POST" || !context.HttpContext.Request.HasFormContentType)
            {
                // todo logging
                return(new TokenErrorResult(OidcConstants.TokenErrors.InvalidRequest));
            }

            // validate client
            var clientResult = await _clientValidator.ValidateAsync(context.HttpContext);

            if (clientResult.Client == null)
            {
                return(new TokenErrorResult(OidcConstants.TokenErrors.InvalidClient));
            }

            // validate request
            var requestResult = await _requestValidator.ValidateRequestAsync(
                context.HttpContext.Request.Form.AsNameValueCollection(),
                clientResult.Client);

            if (requestResult.IsError)
            {
                return(new TokenErrorResult(requestResult.Error, requestResult.ErrorDescription));
            }

            // create response
            var response = await _responseGenerator.ProcessAsync(requestResult.ValidatedRequest);

            // return result
            return(new TokenResult(response));
        }
        private async Task <IEndpointResult> ProcessTokenRequestAsync(HttpContext context)
        {
            // validate client
            var clientResult = await _clientValidator.ValidateAsync(context);

            if (clientResult.Client == null)
            {
                return(Error(OidcConstants.TokenErrors.InvalidClient));
            }

            // validate request
            var form          = (await context.Request.ReadFormAsync()).AsNameValueCollection();
            var requestResult = await _requestValidator.ValidateRequestAsync(form, clientResult);

            if (requestResult.IsError)
            {
                await _events.RaiseAsync(new TokenIssuedFailureEvent(requestResult));

                return(Error(requestResult.Error, requestResult.ErrorDescription, requestResult.CustomResponse));
            }

            // create response
            var response = await _responseGenerator.ProcessAsync(requestResult);

            await _events.RaiseAsync(new TokenIssuedSuccessEvent(response, requestResult));

            // return result
            return(new TokenResult(response));
        }
        private async Task <IEndpointResult> ProcessTokenRequestAsync(IdentityServerContext context)
        {
            _logger.LogInformation("Start token request.");

            // validate client
            var clientResult = await _clientValidator.ValidateAsync(context.HttpContext);

            if (clientResult.Client == null)
            {
                return(new TokenErrorResult(OidcConstants.TokenErrors.InvalidClient));
            }

            // validate request
            var requestResult = await _requestValidator.ValidateRequestAsync(
                context.HttpContext.Request.Form.AsNameValueCollection(),
                clientResult.Client);

            if (requestResult.IsError)
            {
                return(new TokenErrorResult(requestResult.Error, requestResult.ErrorDescription));
            }

            // create response
            var response = await _responseGenerator.ProcessAsync(requestResult.ValidatedRequest);

            // return result
            _logger.LogInformation("Token request success.");
            return(new TokenResult(response));
        }
        public async Task <TokenRawResult> ProcessRawAsync(IFormCollection formCollection)
        {
            _logger.LogTrace("Processing token request.");

            var rawResult = new TokenRawResult();

            // validate HTTP
            if (formCollection.IsNullOrEmpty())
            {
                _logger.LogWarning($"Invalid {nameof(formCollection)} for token endpoint");
                rawResult.TokenErrorResult = Error(OidcConstants.TokenErrors.InvalidRequest);
                return(rawResult);
            }

            var clientId = formCollection[OidcConstants.TokenRequest.ClientId];
            var client   = await _clients.FindEnabledClientByIdAsync(clientId);

            if (client == null)
            {
                _logger.LogError($"No client with id '{clientId}' found. aborting");
                rawResult.TokenErrorResult = Error($"{OidcConstants.TokenRequest.ClientId} bad",
                                                   $"No client with id '{clientId}' found. aborting");
                return(rawResult);
            }

            var clientSecretValidationResult = new ClientSecretValidationResult
            {
                IsError = false,
                Client  = client,
                Secret  = null
            };

            // validate request
            var form = formCollection.AsNameValueCollection();

            _logger.LogTrace("Calling into token request validator: {type}", _requestValidator.GetType().FullName);
            var requestResult = await _requestValidator.ValidateRequestAsync(form, clientSecretValidationResult);

            if (requestResult.IsError)
            {
                await _events.RaiseAsync(new TokenIssuedFailureEvent(requestResult));

                rawResult.TokenErrorResult = Error(requestResult.Error, requestResult.ErrorDescription, requestResult.CustomResponse);
                return(rawResult);
            }

            // create response
            _logger.LogTrace("Calling into token request response generator: {type}", _responseGenerator.GetType().FullName);
            var response = await _responseGenerator.ProcessAsync(requestResult);

            await _events.RaiseAsync(new TokenIssuedSuccessEvent(response, requestResult));

            LogTokens(response, requestResult);

            // return result
            _logger.LogDebug("Token request success.");
            rawResult.TokenResult = new TokenResult(response);
            return(rawResult);
        }
        private async Task <IEndpointResult> ProcessTokenRequestAsync(HttpContext context)
        {
            _logger.LogDebug("Start token request.");
            // validate request
            var form     = (await context.Request.ReadFormAsync()).AsNameValueCollection();
            var userName = form.Get(OidcConstants.TokenRequest.UserName);
            var password = form.Get(OidcConstants.TokenRequest.Password);
            var scope    = form.Get(OidcConstants.TokenRequest.Scope);

            if (scope == "phone_number")
            {
                var getUserByPhoneNumber = await _usersService.GetByPhoneNumberOTP(userName, password);

                if (getUserByPhoneNumber != null)
                {
                    form.Remove("username");
                    form.Remove("password");
                    form.Remove("scope");
                    form.Add("username", getUserByPhoneNumber.Username);
                    form.Add("password", getUserByPhoneNumber.Password);
                    scope = null;
                    //form.Add("scope", "openid");
                }
            }
            // validate client
            var clientResult = await _clientValidator.ValidateAsync(context);

            if (clientResult.Client == null)
            {
                return(Error(OidcConstants.TokenErrors.InvalidClient));
            }

            // validate request
            //var form = (await context.Request.ReadFormAsync()).AsNameValueCollection();
            _logger.LogTrace("Calling into token request validator: {type}", _requestValidator.GetType().FullName);
            var requestResult = await _requestValidator.ValidateRequestAsync(form, clientResult);

            if (requestResult.IsError)
            {
                await _events.RaiseAsync(new TokenIssuedFailureEvent(requestResult));

                return(Error(requestResult.Error, requestResult.ErrorDescription, requestResult.CustomResponse));
            }

            // create response
            _logger.LogTrace("Calling into token request response generator: {type}", _responseGenerator.GetType().FullName);
            var response = await _responseGenerator.ProcessAsync(requestResult);

            await _events.RaiseAsync(new TokenIssuedSuccessEvent(response, requestResult));

            LogTokens(response, requestResult);

            // return result
            _logger.LogDebug("Token request success.");
            return(new TokenResult(response));
        }
        private async Task <IEndpointResult> ProcessTokenRequestAsync(HttpContext context)
        {
            _logger.LogTrace("Start token request.");

            // validate client
            var clientResult = await _clientValidator.ValidateAsync(context);

            if (clientResult.Client == null)
            {
                _logger.LogDebug("Invalid client");
                return(Error(OidcConstants.TokenErrors.InvalidClient));
            }

            // validate request
            var form = (await context.Request.ReadFormAsync()).AsNameValueCollection();

            if (_logger.IsEnabled(LogLevel.Trace))
            {
                _logger.LogTrace("Calling into token request validator: {type}", _requestValidator.GetType().FullName);
            }

            var requestResult = await _requestValidator.ValidateRequestAsync(form, clientResult);

            if (requestResult.IsError)
            {
                _logger.LogDebug("Token issued failure");
                await _events.RaiseAsync(new TokenIssuedFailureEvent(requestResult));

                return(Error(requestResult.Error, requestResult.ErrorDescription, requestResult.CustomResponse));
            }

            _logger.LogDebug("Get IP address and device type");
            requestResult.ValidatedRequest.ClientIp = context.GetRequestIp();
            requestResult.ValidatedRequest.Device   = context
                                                      .GetHeaderValueAs <string>("User-Agent")
                                                      .GetDevice();

            // create response
            if (_logger.IsEnabled(LogLevel.Trace))
            {
                _logger.LogTrace("Calling into token request response generator: {type}", _responseGenerator.GetType().FullName);
            }

            var response = await _responseGenerator.ProcessAsync(requestResult);

            _logger.LogTrace("Raise token issued successfully event");
            await _events.RaiseAsync(new TokenIssuedSuccessEvent(response, requestResult));

            LogTokens(response, requestResult);

            // return result
            _logger.LogDebug("Token request success.");
            return(new TokenResult(response));
        }
Exemple #9
0
        private async Task <IEndpointResult> ProcessTokenRequestAsync(HttpContext context)
        {
            _logger.LogDebug("Start token request.");

            // validate client
            var clientResult = await _clientValidator.ValidateAsync(context);

            if (clientResult.Client == null)
            {
                return(Error(OidcConstants.TokenErrors.InvalidClient));
            }

            // validate request
            var form = (await context.Request.ReadFormAsync()).AsNameValueCollection();

            _logger.LogTrace("Calling into token request validator: {type}", _requestValidator.GetType().FullName);
            var requestResult = await _requestValidator.ValidateRequestAsync(form, clientResult);

            if (requestResult.IsError)
            {
                await _events.RaiseAsync(new TokenIssuedFailureEvent(requestResult));

                return(Error(requestResult.Error, requestResult.ErrorDescription, requestResult.CustomResponse));
            }

            // create response
            _logger.LogTrace("Calling into token request response generator: {type}", _responseGenerator.GetType().FullName);
            var response = await _responseGenerator.ProcessAsync(requestResult);

            await _events.RaiseAsync(new TokenIssuedSuccessEvent(response, requestResult));

            LogTokens(response, requestResult);

            // return result
            _logger.LogDebug("Token request success.");
            return(new TokenResult(response));
        }
Exemple #10
0
        public async Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            var refreshToken = context.Request.Raw.Get("refresh_token");
            var clientId     = context.Request.Raw.Get("client_id");

            if (string.IsNullOrEmpty(refreshToken))
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
                return;
            }
            if (string.IsNullOrEmpty(clientId))
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidClient);
                return;
            }
            var index = clientId.IndexOf(PrependPublic);

            if (index != 0)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidClient);
                return;
            }

            var client = await _clientStore.FindClientByIdAsync(clientId);

            if (client == null)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidClient);
                return;
            }

            var originalClientId = clientId.Substring(PrependPublicIndex);

            if (string.IsNullOrEmpty(originalClientId))
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidClient);
                return;
            }
            var originalClient = await _clientStore.FindClientByIdAsync(originalClientId);

            if (originalClient == null)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidClient);
                return;
            }


            NameValueCollection nvc = new NameValueCollection
            {
                { OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.RefreshToken },
                { OidcConstants.TokenRequest.RefreshToken, refreshToken }
            };

            _validatedRequest = new ValidatedTokenRequest
            {
                Raw     = nvc,
                Client  = originalClient,
                Options = _options
            };
            var result = await ValidateRefreshTokenRequestAsync(nvc);

            if (result.IsError)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
                return;
            }

            result.ValidatedRequest.GrantType           = OidcConstants.GrantTypes.RefreshToken;
            result.ValidatedRequest.AccessTokenLifetime = result.ValidatedRequest.Client.AccessTokenLifetime;
            var refreshResponse = await _tokenResponseGenerator.ProcessAsync(result);

            var dto = new ResultDto
            {
                access_token  = refreshResponse.AccessToken,
                refresh_token = refreshResponse.RefreshToken,
                expires_in    = refreshResponse.AccessTokenLifetime,
                token_type    = OidcConstants.TokenResponse.BearerTokenType
            };
            var response = new Dictionary <string, object>
            {
                { "inner_response", dto }
            };

            context.Result = new GrantValidationResult(customResponse: response);
        }
Exemple #11
0
        public virtual async Task <IdentityUtilsResult <TokenResponse> > GetToken(TokenRequest request)
        {
            var config = HttpContext.RequestServices.GetService(typeof(IIdentityUtilsAuthenticationConfig)) as IIdentityUtilsAuthenticationConfig;

            request.ClientId = config?.ClientId ?? request.ClientId;

            HttpContext.Request.Form = new FormCollection(new Dictionary <string, StringValues>
            {
                { "client_id", request.ClientId },
                { "grant_type", request.GrantType },
                { "username", request.Username },
                { "password", request.Password },
                { "refresh_token", request.RefreshToken },
            });

            // validate client
            var client = await clientStore.FindEnabledClientByIdAsync(request.ClientId);

            var invalidClient = !client.AllowedGrantTypes.Intersect(GrantTypes.ResourceOwnerPassword).Any() && !(request.GrantType == AuthenticationConstants.GrantTypeRefreshToken);

            if (client == null || invalidClient)
            {
                return(IdentityUtilsResult <TokenResponse> .ErrorResult($"Client id not found or invalid grant type"));
            }
            var clientResult = new ClientSecretValidationResult
            {
                IsError = false,
                Client  = client
            };

            var form = new NameValueCollection
            {
                { "client_id", request.ClientId },
                { "grant_type", request.GrantType },
                { "refresh_token", request.RefreshToken },
                { "username", request.Username },
                { "password", request.Password },
            };

            // validate request
            var requestResult = await requestValidator.ValidateRequestAsync(form, clientResult);

            if (requestResult.IsError)
            {
                await events.RaiseAsync(new TokenIssuedFailureEvent(requestResult));

                return(IdentityUtilsResult <TokenResponse> .ErrorResult($"{requestResult.Error} - {requestResult.ErrorDescription}"));
            }

            // create response
            var response = await responseGenerator.ProcessAsync(requestResult);

            await events.RaiseAsync(new TokenIssuedSuccessEvent(response, requestResult));

            // return result
            var tokenResponse = new TokenResponse
            {
                AccessToken  = response.AccessToken,
                RefreshToken = response.RefreshToken,
                Lifetime     = response.AccessTokenLifetime,
                Scopes       = response.Scope.Split(' ')
            };

            return(IdentityUtilsResult <TokenResponse> .SuccessResult(tokenResponse));
        }