Obtain a permanent access token from an authorization code.

@param string $code Authorization code retrieved from the redirect URI.
776507
public function request_access_token($code){
        $params = [
            'client_id' => $this->client_id,
            'client_secret' => $this->client_secret,
            'code' => $code,
            'grant_type' => 'authorization_code',
        ];
        
        $response = $this->requests->post($this->auth_url, [], $params);
        if (!$response->success){
            throw new Auth\Exception('Auth url returned with status code ' . $response->status_code);
        }
        
        $body = json_decode($response->body);
        if (isset($body->error)){
            throw new Auth\Exception("[{$body->error}] {$body->error_description}");
        }
        
        return [
            'store_id' => $body->user_id,
            'access_token' => $body->access_token,
            'scope' => $body->scope,
        ];
    }
742878
public function accessToken ($code, $state) {
		if ($this->validState($state)) {
			throw new \ErrorException('stateが不正です。');
		}

		$result = Curl::url(sprintf('%s%s', $this->host, $this->accessTokenPath))->headers([
			'Authorization'	=> sprintf('Basic %s', base64_encode(sprintf('%s:%s', $this->clientId, $this->secret))),
		])->parameters([
			'response_type'			=> $this->code ?? static::RESPONSE_TYPE_CODE,
			'client_id'				=> $this->clientId,
			'redirect_uri'			=> $this->redirectUri,
			'scope'					=> implode(' ', (array) $this->scope),
			'state'					=> $this->state,
			'code_challenge'		=> $this->codeChallenge,
			'code_challenge_method'	=> $this->codeChallengeMethod ?? static::CODE_CHALLENGE_METHOD_SHA256,
		])->bodies([
			'grant_type'		=> $this->grantType ?? static::GRANT_TYPE_AUTHORIZATION_CODE,
			'code'				=> $code,
			'redirect_uri'		=> $this->redirectUri,
			'client_id'			=> $this->clientId,
			'code_verifier'		=> $this->codeVerifier,
		])->exec();

		$this->tokenInfo	= json_decode($result['body']);

		return $this;
	}
433212
def _authorization_code_flow(self):
        """"""
        options = {
            'scope': getattr(self, 'scope', 'non-expiring'),
            'client_id': self.options.get('client_id'),
            'response_type': 'code',
            'redirect_uri': self._redirect_uri()
        }
        url = '%s%s/connect' % (self.scheme, self.host)
        self._authorize_url = '%s?%s' % (url, urlencode(options))
114434
private function getAccessToken($code)
    {
        $this->logger->debug('Get Access Token.');
        $this->initRequest();
        $token_url = $this->fcBaseUrl.'token';
        $post_data = [
            "grant_type"    => "authorization_code",
            "redirect_uri"  => $this->callbackUrl,
            "client_id"     => $this->clientId,
            "client_secret" => $this->clientSecret,
            "code"          => $code,
        ];
        $this->logger->debug('POST Data to FranceConnect.');
        $this->setPostFields($post_data);
        $response = \Unirest\Request::post($token_url);
        
        // check status code
        if ($response->code != Response::HTTP_OK) {
            $result_array = $response->body;
            $description = array_key_exists(
                "error_description",
                $result_array
            ) ? $result_array["error_description"] : '';
            $this->logger->error(
                $result_array["error"].$description
            );
            throw new Exception("FranceConnectError".$response->code." msg = ".$response->raw_body);
        }
        
        $result_array = $response->body;
        $id_token = $result_array['id_token'];
        $this->session->set(static::ID_TOKEN_HINT, $id_token);
        $all_part = explode(".", $id_token);
        $payload = json_decode(base64_decode($all_part[1]), true);
        
        // check nonce parameter
        if ($payload['nonce'] != $this->session->get(static::OPENID_SESSION_NONCE)) {
            $this->logger->error('The value of the parameter NONCE is not equal to the one which is expected');
            throw new SecurityException("The nonce parameter is invalid");
        }
        // verify the signature of jwt
        $this->logger->debug('Check JWT signature.');
        $jws = SimpleJWS::load($id_token);
        if (!$jws->verify($this->clientSecret)) {
            $this->logger->error('The signature of the JWT is not valid.');
            throw new SecurityException("JWS is invalid");
        }
        
        $this->session->remove(static::OPENID_SESSION_NONCE);
        
        return $result_array['access_token'];
    }
689140
public function getToken($code)
	{
		$request = 	new Request('POST', 'token', [], http_build_query([
			'redirect_uri'  => $this->getRedirectUri(),
			'client_id'		=> $this->getClientId(),
			'client_secret' => $this->getClientSecret(),
			'grant_type' 	=> 'authorization_code',
			'code' 			=> $code
		]));

		try {
			$response = $this->getHttpClient()->send($request);
		} catch (\Exception $e) {
			throw new SurveyMonkeyApiException($e->getMessage(), $e->getCode(), $e);
		}

		if (!$response->hasHeader('content-type') || !preg_match('/application\/json/i', $response->getHeader('content-type')[0])) {
			throw new SurveyMonkeyApiException(spritnf('Response expected to be a JSON response. Received %s', $response->getHeader('content-type')[0]));
		}

		return json_decode($response->getBody(), true);
	}
1216019
public function token($code) {
        if (!is_array($code)) {
            $code = [
                'code' => $code,
            ];
        }
        return $this->getToken()->parameters($code)->text();
    }
323176
public function getAuthorizationCode($code)
    {
        $code = $this->getObjectByType('code_table',$code);

        return is_null($code) ? false : $code;
    }
951727
public function authenticate($code)
    {
        // Validate code
        if (!$code || strlen($code) != 6) {
            throw new Exception('Invalid authorization code');
        }

        // Check for required items
        if (!$this->clientId) {
            throw new Exception('Client ID is required');
        }
        if (!$this->clientSecret) {
            throw new Exception('Client secret is required');
        }
        if (!$this->redirectUri) {
            throw new Exception('Redirect URI is required');
        }

        $fields = [
            'client_id'     => $this->clientId,
            'client_secret' => $this->clientSecret,
            'code'          => $code,
            'redirect_uri'  => urlencode($this->redirectUri),
            'grant_type'    => 'authorization_code'
        ];

        $url  = 'https://';
        $url .= $this->level . '.';
        $url .= (!empty($this->environment)) ? $this->environment . '.' : '';
        $url .= self::HOSTNAME . '/' . self::TOKEN;

        $this->http->setUrl($url)
                   ->setPostFields($fields)
                   ->setHeader(['Accept' => 'application/json']);

        $data = json_decode($this->http->execute());

        if (isset($data->access_token)) {
            $this->setAccessToken($data->access_token);
            $this->setOrcid($data->orcid);
        } else {
            // Seems like the response format changes on occasion...not sure what's going on there?
            $error = (isset($data->error_description)) ? $data->error_description : $data->{'error-desc'}->value;

            throw new Exception($error);
        }

        return $this;
    }
1316540
public function fetchAccessToken($redirect_code)
    {
        $http = $this->getHTTPClient();
        $post_data = [
            'client_id' => $this->client_id,
            'client_secret' => $this->client_secret,
            'grant_type' => 'authorization_code',
            'code' => $redirect_code,
            'redirect_uri' => $this->getRedirectURL(),
        ];
        // Request access token
        try {
            $response = $http->request('POST', 'oauth/access_token', [
                'form_params' => $post_data
            ]);

            $responseBody = $response->getBody();
            $responseArr = json_decode($responseBody, true);

            //Set new data into the config and update the current instance
            $this->setAccessToken($responseArr['access_token']);
            $this->setAccessTokenExpire($responseArr['expires_in']);
            $this->setRefreshToken($responseArr['refresh_token']);
        } catch (\Exception  $exception) {
            $this->handleException($exception);
        }
    }
418860
private function acquireToken($code)
    {
        // Request the token
        $client = new Client(); //GuzzleHttp\Client

        try {
            $response = $client->post($this->token_endpoint, [
                'form_params' => $this->getAccessTokenFields($code),
                'curl' => $this->setOauthCurlopts(),
                'synchronous' => true,
            ]);

            // Get the token and type from the response
            return json_decode($response->getBody(), true);

        } catch (\GuzzleException $e) {

            return false;
        }
    }
192627
public function authenticate($provider, $code=False)
    {
        if($code){
            return $this->handleProviderCallback($provider);
        }

        return $this->redirectToProvider($provider);
    }
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)
  })
}
729996
public function get($code)
    {
        foreach ($this->getDbConnection()->fetchAll(
            'SELECT * from oauth_auth_code
            WHERE auth_code = :authCode AND expire_time > :ts',
            [
                'authCode' => $code,
                'ts' => time()
            ]
        ) as $row) {
            if ($row) {
                return (new AuthCodeEntity($this->server))
                    ->setRedirectUri($row['client_redirect_uri'])
                    ->setExpireTime($row['expire_time'])
                    ->setId($row['auth_code']);
            }
        }
        return null;
    }
495332
public function requestToken($code)
    {
        $parameters = [
            'client_id' => config('twitch-api.client_id'),
            'client_secret' => config('twitch-api.client_secret'),
            'redirect_uri' => config('twitch-api.redirect_url'),
            'code' => $code,
            'grant_type' => 'authorization_code'
        ];

        try {
            $client = new Client();

            $response = $client->post(config('twitch-api.api_url') . '/kraken/oauth2/token', ['body' => $parameters]);

            $response = $response->json();

            if (isset($response[ 'access_token' ])) {

                return $response[ 'access_token' ];
            }

        } catch (\Exception $e) {

            throw $e;
        }
    }
125944
public function getAuthorizationCode($code)
    {
        if (!isset($this->authorizationCodes[$code])) {
            return false;
        }

        return array_merge(array(
            'authorization_code' => $code,
        ), $this->authorizationCodes[$code]);
    }
599912
public function getTokenForCode($code, $state)
    {
        if ($state != $_SESSION['oauth2_lockme_state']) {
            unset($_SESSION['oauth2_lockme_state']);
            throw new \Exception("Wrong state");
        }
        unset($_SESSION['oauth2_lockme_state']);

        $this->accessToken = $this->provider->getAccessToken('authorization_code', [
        'code' => $code
    ]);
        return $this->accessToken;
    }
955721
public function getAccessToken($code = null) {
        if ($this->debug) { $start = microtime(true); }
        if ($code) {
            // todo get access_token via authorization_code request
            $params['client_id']     = $this->getClientID();
            $params['client_secret'] = $this->getClientSecret();
            $params['redirect_uri']  = $this->getRedirectUri();
            $params['grant_type']    = 'authorization_code';
            $params['scope']         = '';
            $params['state']         = '';
            $params['code']          = $code;
            $access_token = (array) json_decode($this->makeRequest($this->getTokenURL(), $params));
        } else {
            if ($this->accessToken) {
                return $this->accessToken;
            } else {
                $session = $this->getSession();
                // either user session signed, or app signed
                if (isset($session['access_token'])) {
                    $access_token = $session['access_token'];
                } else {
                    // No success! Defaults to
                    $access_token = $this->getClientID();
                }
            }
        }
        if ($this->debug) { $this->timer[__FUNCTION__]['elapsed'][] = microtime(true)-$start; }
        return $access_token;
    }