@param ServerRequestInterface $request
@param ClientEntityInterface  $client

@throws OAuthServerException

@return UserEntityInterface
194952
protected function validateUser(ServerRequestInterface $request, ClientEntityInterface $client)
	{
		$accessToken = $this->getRequestParameter('accessToken', $request);
		if (is_null($accessToken)) {
		  throw OAuthServerException::invalidRequest('accessToken');
		}

		$provider = $this->getRequestParameter('provider', $request);
		if (is_null($provider)) {
		  throw OAuthServerException::invalidRequest('provider');
		}

		$user = $this->userRepository->getUserFromSocialProvider(
		  $accessToken,
		  $provider,
		  $this->getIdentifier(),
		  $client
		);
		if ($user instanceof UserEntityInterface === false) {
		  $this->getEmitter()->emit(new RequestEvent(RequestEvent::USER_AUTHENTICATION_FAILED, $request));

		  throw OAuthServerException::invalidCredentials();
		}

		return $user;
	}
520712
public function send(RequestInterface $request, array $options = [])
    {
        $response = parent::send($request, $options);

        // re-authenticate if 403 and token is expired
        if (
            $this->token &&
            $response->getStatusCode() === 403 &&
            $this->isTokenExpired($this->token) &&
            !$this->authenticate()
        ) {
            throw new ClientException('Cannot re-authenticate.');
        }

        $this->checkResponse($response);

        return $response;
    }
1096041
public function executeAsync(ClientRequestInterface $request, array $headers = null, array $clientOptions = [])
    {
        if ($request instanceof ContextAwareInterface) {
            $request->setContextIfNull($this->getConfig()->getContext());
        }
        $httpRequest = $this->createHttpRequest($request, $headers);
        $client = $this->getHttpClient();
        if ($client instanceof AdapterOptionInterface) {
            $response = $request->buildResponse($client->executeAsync($httpRequest, $clientOptions));
        } else {
            $response = $request->buildResponse($client->executeAsync($httpRequest));
        }

        $response = $response->then(
            function ($httpResponse) use ($httpRequest) {
                $this->logDeprecatedRequest($httpResponse, $httpRequest);
                return $httpResponse;
            }
        );

        return $response;
    }
274570
public function oauthCallbackAction(Request $request, Session $session, Client $client): RedirectResponse
    {
        // Give up if the required GET params or stored request token don't exist.
        if (!$request->get('oauth_verifier')) {
            throw $this->createNotFoundException('No OAuth verifier given.');
        }
        if (!$session->has('oauth.request_token')) {
            throw $this->createNotFoundException('No request token found. Please try logging in again.');
        }

        // Complete authentication.
        $token = $session->get('oauth.request_token');
        $verifier = $request->get('oauth_verifier');
        $accessToken = $client->complete($token, $verifier);

        // Store access token, and remove request token.
        $session->set('oauth.access_token', $accessToken);
        $session->remove('oauth.request_token');

        // Regenerate session ID.
        $session->migrate();

        // Store user identity.
        $ident = $client->identify($accessToken);
        $session->set('logged_in_user', $ident);

        // Send to homepage.
        return $this->redirectToRoute('home');
    }
393331
public function getUser(ServerRequestInterface $request)
    {
        $server = $request->getServerParams();
        if (!isset($server['PHP_AUTH_USER']) || !isset($server['PHP_AUTH_PW'])) {
            return null;
        }

        $username = $server['PHP_AUTH_USER'];
        $password = $server['PHP_AUTH_PW'];

        if (!is_string($username) || $username === '' || !is_string($password) || $password === '') {
            return null;
        }

        return $this->_identifier->identify([
            IdentifierInterface::CREDENTIAL_USERNAME => $username,
            IdentifierInterface::CREDENTIAL_PASSWORD => $password,
        ]);
    }
343616
public function findOneByClientAndRefreshToken(ApiClientInterface $client, $refreshToken)
    {
        $qb = $this->createQueryBuilder();

        $qb->field('client.id')->equals($client->getId());
        $qb->field('refreshCode')->equals($refreshToken);
        $qb->limit(1);

        return $qb->getQuery()->getSingleResult();
    }
290602
protected function passIssueToken(array $parameters, ClientInterface $determinedClient = null): ResponseInterface
    {
        // if client is not given we interpret it as a 'default' client should be used
        if ($determinedClient === null) {
            $determinedClient = $this->passGetIntegration()->passReadDefaultClient();
            if ($determinedClient->hasCredentials() === true) {
                throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_UNAUTHORIZED_CLIENT);
            }
        }

        if ($determinedClient !== null && $determinedClient->isPasswordGrantEnabled() === false) {
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_UNAUTHORIZED_CLIENT);
        }

        $scope = $this->passGetScope($parameters);
        list ($isScopeValid, $scopeList, $isScopeModified) =
            $this->passGetIntegration()->passValidateScope($determinedClient, $scope);
        if ($isScopeValid === false) {
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_SCOPE);
        }

        if (($userName = $this->passGetUserName($parameters)) === null ||
            ($password = $this->passGetPassword($parameters)) === null
        ) {
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_REQUEST);
        }

        $response = $this->passGetIntegration()->passValidateCredentialsAndCreateAccessTokenResponse(
            $userName,
            $password,
            $determinedClient,
            $isScopeModified,
            $scopeList,
            $parameters
        );

        return $response;
    }
563407
protected function validateOldRefreshToken(ServerRequestInterface $request, $clientId)
    {
        $encryptedRefreshToken = $this->getRequestParameter('refresh_token', $request);
        if (is_null($encryptedRefreshToken)) {
            throw OAuthServerException::invalidRequest('refresh_token');
        }

        // Validate refresh token
        try {
            $refreshToken = $this->decrypt($encryptedRefreshToken);
        } catch (Exception $e) {
            throw OAuthServerException::invalidRefreshToken('Cannot decrypt the refresh token', $e);
        }

        $refreshTokenData = json_decode($refreshToken, true);
        if ($refreshTokenData['client_id'] !== $clientId) {
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_CLIENT_FAILED, $request));
            throw OAuthServerException::invalidRefreshToken('Token is not linked to client');
        }

        if ($refreshTokenData['expire_time'] < time()) {
            throw OAuthServerException::invalidRefreshToken('Token has expired');
        }

        if ($this->refreshTokenRepository->isRefreshTokenRevoked($refreshTokenData['refresh_token_id']) === true) {
            throw OAuthServerException::invalidRefreshToken('Token has been revoked');
        }

        return $refreshTokenData;
    }
270261
public function createTokenResponse(
        ServerRequestInterface $request,
        Client $client = null,
        TokenOwnerInterface $owner = null
    ): ResponseInterface {
        $postParams = $request->getParsedBody();

        $code = $postParams['code'] ?? null;

        if (null === $code) {
            throw OAuth2Exception::invalidRequest('Could not find the authorization code in the request');
        }

        /* @var \ZfrOAuth2\Server\Model\AuthorizationCode $authorizationCode */
        $authorizationCode = $this->authorizationCodeService->getToken($code);

        if (null === $authorizationCode || $authorizationCode->isExpired()) {
            throw OAuth2Exception::invalidGrant('Authorization code cannot be found or is expired');
        }

        $clientId = $postParams['client_id'] ?? null;

        if ($authorizationCode->getClient()->getId() !== $clientId) {
            throw OAuth2Exception::invalidRequest(
                'Authorization code\'s client does not match with the one that created the authorization code'
            );
        }

        // If owner is null, we reuse the same as the authorization code
        $owner = $owner ?: $authorizationCode->getOwner();

        // Everything is okey, let's start the token generation!
        $scopes = $authorizationCode->getScopes(); // reuse the scopes from the authorization code

        $accessToken = $this->accessTokenService->createToken($owner, $client, $scopes);

        // Before generating a refresh token, we must make sure the authorization server supports this grant
        $refreshToken = null;

        if ($this->authorizationServer->hasGrant(RefreshTokenGrant::GRANT_TYPE)) {
            $refreshToken = $this->refreshTokenService->createToken($owner, $client, $scopes);
        }

        return $this->prepareTokenResponse($accessToken, $refreshToken);
    }
729509
public function addClient(\Gpupo\CommonSchema\ORM\Entity\Application\API\OAuth\Client\Client $client)
    {
        $this->clients[] = $client;

        return $this;
    }
212111
public function deleteClientAction(Client $client)
    {
        $oldid = $client->getId();
        $this->oauthManager->deleteClient($client);

        return new JsonResponse(['id' => $oldid]);
    }
461109
public function execute(RequestInterface $request): RequestInterface
    {
        if ($request->getUri()->getPath() === self::ENDPOINT_INSTALLATION) {
            return $request;
        } else {
            $signature = $this->determineRequestSignature(
                $request->getUri(),
                $request->getMethod(),
                $request->getBody()->getContents(),
                $request->getHeaders()
            );

            return $request->withHeader(self::HEADER_CLIENT_SIGNATURE, $signature);
        }
    }
1121034
public function updateClient(ClientInterface $client)
    {
        if (isset($this->clients[$client->getAccessToken()])) {
            $this->clients[$client->getAccessToken()] = $client;
        }
    }
818123
private function chooseHttpClient(RequestInterface $request)
    {
        foreach ($this->clients as $client) {
            if ($client['matcher']->matches($request)) {
                return $client['client'];
            }
        }

        throw new HttpClientNoMatchException('No client found for the specified request', $request);
    }
1367020
public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $user_id = (int) $request->getParsedBody()['user_id'];

        $user = $this->user_service->find($user_id);

        if ($user === null) {
            throw new NotFoundHttpException('User ID ' . $user_id . ' not found');
        }

        if ($this->user->id() !== $user_id) {
            Log::addAuthenticationLog('Masquerade as user: ' . $user->userName());
            Auth::login($user);
            Session::put('masquerade', '1');
        }

        return response('', StatusCodeInterface::STATUS_NO_CONTENT);
    }
587816
public function validateAuthorization(ServerRequestInterface $request)
    {
        $user = $this->app->make(User::class);

        // Allow logged in users to bypass API authentication entirely if the route allows it
        // This functionality is NOT READY. We will not allow this yet.
        /*
        $route = $request->getAttribute('_route');

        if ($user->checkLogin()) {
            // Return the request with additional attributes
            return $request
                ->withAttribute('oauth_access_token_id', null)
                ->withAttribute('oauth_client_id', null)
                ->withAttribute('oauth_user_id', null)
                ->withAttribute('oauth_scopes', 'session');

            return $request;
        }
        */

        // Delegate the rest to the passed in validator
        return $this->validator->validateAuthorization($request);
    }
619393
public function issueToken(ServerRequestInterface $request)
    {
        $response = $this->withErrorHandling(function () use ($request) {
            $input = (array) $request->getParsedBody();
            $clientId = isset($input['client_id']) ? $input['client_id'] : null;

            // Overwrite password grant at the last minute to add support for customized TTLs
            $this->server->enableGrantType(
                $this->makePasswordGrant(), LumenPassport::tokensExpireIn(null, $clientId)
            );

            return $this->server->respondToAccessTokenRequest($request, new Psr7Response);
        });

        if ($response->getStatusCode() < 200 || $response->getStatusCode() > 299) {
            return $response;
        }

        $payload = json_decode($response->getBody()->__toString(), true);

        if (isset($payload['access_token'])) {
            $tokenId = $this->jwt->parse($payload['access_token'])->getClaim('jti');
            $token = $this->tokens->find($tokenId);

            if ($token->client->firstParty() && LumenPassport::$allowMultipleTokens) {
                // We keep previous tokens for password clients
            } else {
                $this->revokeOrDeleteAccessTokens($token, $tokenId);
            }
        }

        return $response;
    }