Validate the authorization code.

@param stdClass               $authCodePayload
@param ClientEntityInterface  $client
@param ServerRequestInterface $request
196571
private function validateAuthorizationCode(
        $authCodePayload,
        ClientEntityInterface $client,
        ServerRequestInterface $request
    ) {
        if (time() > $authCodePayload->expire_time) {
            throw OAuthServerException::invalidRequest('code', 'Authorization code has expired');
        }

        if ($this->authCodeRepository->isAuthCodeRevoked($authCodePayload->auth_code_id) === true) {
            throw OAuthServerException::invalidRequest('code', 'Authorization code has been revoked');
        }

        if ($authCodePayload->client_id !== $client->getIdentifier()) {
            throw OAuthServerException::invalidRequest('code', 'Authorization code was not issued to this client');
        }

        // The redirect URI is required in this request
        $redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
        if (empty($authCodePayload->redirect_uri) === false && $redirectUri === null) {
            throw OAuthServerException::invalidRequest('redirect_uri');
        }

        if ($authCodePayload->redirect_uri !== $redirectUri) {
            throw OAuthServerException::invalidRequest('redirect_uri', 'Invalid redirect URI');
        }
    }
718326
public function validateAndParseWebhookNotificationFromRequest(\Symfony\Component\HttpFoundation\Request $request) {
        $json_data = json_decode($request->getContent(), true);
        if (!is_array($json_data)) { throw new AuthorizationException("Invalid webhook data received"); }

        // make sure the message is signed properly
        //   throws an exception if invalid
        $this->validateWebhookNotification($json_data);

        return $this->parseWebhookNotificationData($json_data);
    }
896007
function authorizationCodeGrant (code, done) {
  var endpoint = this.endpoints.token
  var provider = this.provider
  var client = this.client
  var url = endpoint.url
  var method = endpoint.method && endpoint.method.toLowerCase()
  var auth = endpoint.auth
  var parser = endpoint.parser
  var accept = endpoint.accept || 'application/json'
  var params = {}

  // required token parameters
  params.grant_type = 'authorization_code'
  params.code = code
  params.redirect_uri = provider.redirect_uri

  // start building the request
  var req = request[method || 'post'](url)

  // Authenticate the client with HTTP Basic
  if (auth === 'client_secret_basic') {
    req.set('Authorization', 'Basic ' + this.base64credentials())
  }

  // Authenticate the client with POST params
  if (auth === 'client_secret_post') {
    params.client_id = client.client_id
    params.client_secret = client.client_secret
  }

  // Add request body params and set other headers
  req.send(qs.stringify(params))
  req.set('accept', accept)
  req.set('user-agent', agent)

  // Execute the request
  return req.end(function (err, res) {
    if (err) { return done(err) }
    var response = (parser === 'x-www-form-urlencoded')
      ? qs.parse(res.text)
      : res.body

    if (res.statusCode !== 200) {
      return done(response)
    }

    done(null, response)
  })
}
788840
private function storeRequest(AuthorizationRequest $request)
    {
        $data = [
            'user' => $request->getUser() ? $request->getUser()->getIdentifier() : null,
            'client' => $request->getClient()->getIdentifier(),
            'challenge' => $request->getCodeChallenge(),
            'challenge_method' => $request->getCodeChallengeMethod(),
            'grant_type' => $request->getGrantTypeId(),
            'redirect' => $request->getRedirectUri(),
            'scopes' => $request->getScopes(),
            'state' => $request->getState(),
            'approved' => (bool) $request->isAuthorizationApproved()
        ];

        /** @var Client $client */
        $client = $request->getClient();
        $clientId = $client->getClientKey();
        $this->session->set("authn_request.$clientId", $data);
    }
883649
public function isDoiAuthenticatedClients($doiValue, $client_id = null)
    {
        if ($client_id === null) {
            return false;
        }

        $client = $this->getAuthenticatedClient();

        if ($client->client_id != $client_id) {
            return false;
        }

        // everyone has access to test prefix
        if (strpos($doiValue, DOIServiceProvider::$globalTestPrefix) === 0) {
            return true;
        }

        // check if the client owns the prefix
        foreach ($client->prefixes as $clientPrefix) {
            if (strpos($doiValue, $clientPrefix->prefix->prefix_value) === 0) {
                return true;
            }
        }

        return false;
    }
1243873
public static void validateSslCertificate() {
        final NetworkHttpClient client = new NetworkHttpClient();
        final Request request = new Request(HttpMethod.GET, "https://api.twilio.com:8443");

        try {
            final Response response = client.makeRequest(request);

            if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) {
                throw new CertificateValidationException(
                    "Unexpected response from certificate endpoint", request, response
                );
            }
        } catch (final ApiException e) {
            throw new CertificateValidationException("Could not get response from certificate endpoint", request);
        }
    }
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);
    }
438938
protected function validateUser(ServerRequestInterface $request, ClientEntityInterface $client)
    {
        $username = $this->getRequestParameter('username', $request);
        if (is_null($username)) {
            throw OAuthServerException::invalidRequest('username');
        }

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

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

            throw OAuthServerException::invalidCredentials();
        }

        return $user;
    }
1307093
protected function auth($client, $authUrlParams = [])
    {
        if ($client instanceof OAuth2) {
            return $this->authOAuth2($client, $authUrlParams);
        } elseif ($client instanceof OAuth1) {
            return $this->authOAuth1($client, $authUrlParams);
        } elseif ($client instanceof OpenId) {
            return $this->authOpenId($client);
        }

        throw new NotSupportedException('Provider "' . get_class($client) . '" is not supported.');
    }
884966
public function authenticate()
    {
        $request = ServerRequest::fromGlobals();
        try {
            return $this->resourceServer->validateAuthenticatedRequest($request);
        } catch (OAuthServerException $exception) {
            $message = $exception->getMessage();
            if ($hint = $exception->getHint()) {
                $message .= ' (' . $hint . ')';
            }
            throw Exception::clientException($message, $exception->getHttpStatusCode(), $exception->getErrorType(), $exception->getHttpStatusCode());
        } catch (\Exception $exception) {
            throw Exception::serverException($exception->getMessage(), $exception->getCode());
        }
    }
940417
public Credential authenticate(String authorizationCode, String userId) throws AuthException {
        Preconditions.checkNotNull(authorizationCode, "Authorization code must not be null");
        AuthorizationCodeTokenRequest tokenRequest = authorizationCodeFlow.newTokenRequest(authorizationCode);

        TokenResponse tokenResponse;
        try {
            tokenResponse = tokenRequest
                    .setRedirectUri(redirectUri)
                    .setScopes(scopes)
                    .execute();
        } catch (IOException e) {
            throw new AuthException("Unable to request token.", e);
        }
        try {
            return authorizationCodeFlow.createAndStoreCredential(tokenResponse, userId);
        } catch (IOException e) {
            throw new AuthException("Unable to create and store credential.", e);
        }
    }
568013
function validate(activationCode) {

    if(!activationCode || !Utils.isString(activationCode)) {
      throw new Error('Activation code must be a string.');
    }
    if (this.type && this.type === 'anonymous') {
      throw new Error("Anonymous users can't be validated.");
    }

    var scope = this.scope, path = this.path;

    // If validate is called from the entity, the scope is the
    // resource's scope
    if(this.id){
      scope = this.resource.scope;
      path = this.resource.path + '/' + this.id;
    }

    // Activate newly created user.
    return EVT.api({
      url: path + '/validate',
      method: 'post',
      authorization: scope.apiKey,
      data: {
        activationCode: activationCode
      }
    });
  }
444142
public function authenticate($authorizationCode)
    {
        $tokens = $this->client->requestTokens(
            $authorizationCode,
            $this->clientId,
            $this->clientSecret,
            $this->redirectUrl
        );

        $this->accessToken = $tokens->access_token;
        $this->refreshToken = $tokens->refresh_token;
        $this->expires = $tokens->expires_at;

        $this->client->authenticate($this->accessToken);
    }
410261
public function verify(SignedJwt $jwt, VerificationContext $verificationContext, array &$errors) : bool
    {
        $verifiers = [
            new SignatureVerifier($verificationContext->getSigner()),
            new AudienceVerifier($verificationContext->getAudience()),
            new ExpirationVerifier(),
            new NotBeforeVerifier(),
            new IssuerVerifier($verificationContext->getIssuer()),
            new SubjectVerifier($verificationContext->getSubject())
        ];
        $isVerified = true;

        /** @var IVerifier $verifier */
        foreach ($verifiers as $verifier) {
            $error = '';

            if (!$verifier->verify($jwt, $error)) {
                $isVerified = false;
                $errors[] = $error;
            }
        }

        return $isVerified;
    }
1025607
public function validateAccessToken($httpHeadersOnly = false, $accessToken = null)
    {
        return $this->checker->isValidRequest($httpHeadersOnly, $accessToken);
    }
1283116
public function handleAuthorize(string $authCode = null)
    {
        $params = [
            'component_appid' => $this->app['config']['app_id'],
            'authorization_code' => $authCode ?? $this->app['request']->get('auth_code'),
        ];

        return $this->httpPostJson('cgi-bin/component/api_query_auth', $params);
    }
1373040
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        // The user provider should implement JWTUserProviderInterface
        if (!$userProvider instanceof JWTUserProviderInterface) {
            throw new InvalidArgumentException('Argument must implement interface Auth0\JWTAuthBundle\Security\Core\JWTUserProviderInterface');
        }

        if ($token->getCredentials() === null) {
            $user = $userProvider->getAnonymousUser();
        } else {
            // Get the user for the injected UserProvider
            $user = $userProvider->loadUserByJWT($token->getCredentials());

            if (!$user) {
                throw new AuthenticationException(sprintf('Invalid JWT.'));
            }
        }

        return new PreAuthenticatedToken(
            $user,
            $token,
            $providerKey,
            $user->getRoles()
        );
    }