/* OAuth2_Storage_AuthorizationCodeInterface
15779
public function getAuthorizationCode($code)
    {
        $stmt = $this->db->prepare(sprintf('SELECT * from %s where authorization_code = :code', $this->config['code_table']));
        $stmt->execute(compact('code'));

        if ($code = $stmt->fetch()) {
            // convert date string back to timestamp
            $code['expires'] = strtotime($code['expires']);
        }

        return $code;
    }
724448
public function getAuthorizerAuthInfo($code)
    {
        $body = $this->parseJSON('json', [
            self::API_GET_AUTHORIZER_AUTH_INFO,
            [
                'component_appid'    => $this->getAccessToken()->getAppId(),
                'authorization_code' => $code,
            ]
        ]);

        return $body;
    }
735452
function OAuth2Error(message, code, uri, status) {
  Error.call(this);
  this.message = message;
  this.code = code || 'server_error';
  this.uri = uri;
  this.status = status || 500;
}
1085534
public function initOauth2Server()
    {
        if ($this->serverInitialized) {
            return;
        }

        $this->serverInitialized = true;
        $this->modelMap = array_merge($this->defaultModelMap, $this->modelMap);
        $this->storageMap = array_merge($this->defaultStorageMap, $this->storageMap);
        foreach ($this->modelMap as $name => $definition) {
            Yii::$container->set(models::class . '\\' . $name, $definition);
        }

        foreach ($this->storageMap as $name => $definition) {
            Yii::$container->set($name, $definition);
        }

        $storages = [];
        foreach(array_keys($this->storageMap) as $name) {
            $storages[$name] = Yii::$container->get($name);
        }

        $grantTypes = [];
        foreach($this->grantTypes as $name => $options) {
            if(!isset($storages[$name]) || empty($options['class'])) {
                throw new InvalidConfigException(
                    'Invalid grant types configuration.'
                );
            }

            $class = $options['class'];
            unset($options['class']);

            $reflection = new ReflectionClass($class);
            $config = array_merge([0 => $storages[$name]], [$options]);

            $instance = $reflection->newInstanceArgs($config);
            $grantTypes[$name] = $instance;
        }

        $this->set('server', Yii::$container->get(Server::class, [
            $this,
            $storages,
            [
                'token_param_name' => $this->tokenParamName,
                'access_lifetime' => $this->tokenAccessLifetime,
            ],
            $grantTypes
        ]));
        $this->set('request', Request::createFromGlobals());
        $this->set('response', new Response());
    }
815837
protected function __getAccessToken($storeState, $code = null, $state = null)
	{
		$this->result = $this->http->get($this->getUrl('sns/oauth2/access_token', array(
			'appid'			=>	$this->appid,
			'secret'		=>	$this->appSecret,
			'code'			=>	isset($code) ? $code : (isset($_GET['code']) ? $_GET['code'] : ''),
			'grant_type'	=>	'authorization_code',
		)))->json(true);
		if(isset($this->result['errcode']) && 0 != $this->result['errcode'])
		{
			throw new ApiException($this->result['errmsg'], $this->result['errcode']);
		}
		else
		{
			switch((int)$this->openidMode)
			{
				case OpenidMode::OPEN_ID:
					$this->openid = $this->result['openid'];
					break;
				case OpenidMode::UNION_ID:
					$this->openid = $this->result['unionid'];
					break;
				case OpenidMode::UNION_ID_FIRST:
					$this->openid = empty($this->result['unionid']) ? $this->result['openid'] : $this->result['unionid'];
					break;
			}
			return $this->accessToken = $this->result['access_token'];
		}
	}
131021
public function getAuthorizationCode($code)
    {
        $sql  = sprintf('SELECT * from %s where authorization_code = :code', $this->config['code_table']);
        $code = $this->fetch($sql, compact('code'));
        if ($code) {
            // convert date string back to timestamp
            $code['expires'] = strtotime($code['expires']);
        }

        return $code;
    }
962731
public ProviderAuthenticationResult handleAuthorizationCode(HttpServletRequest req,
            HttpServletResponse res,
            String authzCode,
            String responseState,
            ConvergedClientConfig clientConfig) {

        String clientId = clientConfig.getClientId();
        OidcClientRequest oidcClientRequest = (OidcClientRequest) req.getAttribute(ClientConstants.ATTRIB_OIDC_CLIENT_REQUEST);
        ProviderAuthenticationResult oidcResult = null;
        oidcResult = authenticatorUtil.verifyResponseState(req, res, responseState, clientConfig);
        if (oidcResult != null) {
            return oidcResult; // only if something bad happened, otherwise proceed to exchange auth code for tokens.
        }
        if (!OIDCClientAuthenticatorUtil.checkHttpsRequirement(clientConfig, clientConfig.getTokenEndpointUrl())) {
            Tr.error(tc, "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS", clientConfig.getTokenEndpointUrl());
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            return oidcResult;
        }
        String redirect_url = authenticatorUtil.setRedirectUrlIfNotDefined(req, clientConfig);
        if (!OIDCClientAuthenticatorUtil.checkHttpsRequirement(clientConfig, redirect_url)) {
            Tr.error(tc, "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS", redirect_url);
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            return oidcResult;
        }

        SSLSocketFactory sslSocketFactory = null;
        try {
            sslSocketFactory = getSSLSocketFactory(clientConfig.getTokenEndpointUrl(), clientConfig.getSSLConfigurationName(), clientId);
        } catch (SSLException e) {
            Tr.error(tc, "OIDC_CLIENT_HTTPS_WITH_SSLCONTEXT_NULL", new Object[] { e.getMessage() != null ? e.getMessage() : "invalid ssl context", clientConfig.getClientId() });
            return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }

        // go get the tokens and validate them.
        try {

            String url = clientConfig.getTokenEndpointUrl();
            if (url == null || url.length() == 0) {
                throw new MalformedURLException("MalformedURLException");
            }
            HashMap<String, String> tokens = oidcClientUtil.getTokensFromAuthzCode(url,
                    clientId,
                    clientConfig.getClientSecret(),
                    redirect_url,
                    authzCode,
                    clientConfig.getGrantType(),
                    sslSocketFactory,
                    clientConfig.isHostNameVerificationEnabled(),
                    clientConfig.getTokenEndpointAuthMethod(),
                    OIDCClientAuthenticatorUtil.getResources(clientConfig),
                    clientConfig.getTokenRequestParams(),
                    clientConfig.getUseSystemPropertiesForHttpClientConnections());

            oidcClientRequest.setTokenType(ClientConstants.TYPE_ID_TOKEN);

            // this has a LOT of dependencies.
            oidcResult = jose4jUtil.createResultWithJose4J(responseState, tokens, clientConfig, oidcClientRequest);

            //if tokens were valid, go get the userinfo if configured to do so, and update the authentication result to include it.
            UserInfoHelper uih = new UserInfoHelper(clientConfig);
            if (uih.willRetrieveUserInfo()) {
                OidcTokenImplBase idToken = null;
                if (oidcResult.getCustomProperties() != null) {
                    idToken = (OidcTokenImplBase) oidcResult.getCustomProperties().get(Constants.ID_TOKEN_OBJECT);
                }
                String subjFromIdToken = null;
                if (idToken != null) {
                    subjFromIdToken = idToken.getSubject();
                }
                if (subjFromIdToken != null) {
                    uih.getUserInfo(oidcResult, sslSocketFactory, tokens.get(Constants.ACCESS_TOKEN), subjFromIdToken);
                }
            }

        } catch (BadPostRequestException e) {
            Tr.error(tc, "OIDC_CLIENT_TOKEN_REQUEST_FAILURE", new Object[] { e.getErrorMessage(), clientId, clientConfig.getTokenEndpointUrl() });
            sendErrorJSON(res, e.getStatusCode(), "invalid_request", e.getErrorMessage());
            oidcResult = new ProviderAuthenticationResult(AuthResult.FAILURE, e.getStatusCode());
        } catch (Exception e) {
            Tr.error(tc, "OIDC_CLIENT_TOKEN_REQUEST_FAILURE", new Object[] { e.getLocalizedMessage(), clientId, clientConfig.getTokenEndpointUrl() });
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }
        return oidcResult;
    }
1133033
public function requestAccessToken($authorizationCode)
    {
        $parameters = [
            'client_id' => $this->getClientId(),
            'client_secret' => $this->getClientSecret(),
            'code' => $authorizationCode,
            'grant_type' => 'authorization_code',
            'redirect_uri' => $this->getRedirectUri(),
        ];

        $response = $this->request->account('POST', '/api/token', $parameters, []);
        $response = $response['body'];

        if (isset($response->refresh_token) && isset($response->access_token)) {
            $this->refreshToken = $response->refresh_token;
            $this->accessToken = $response->access_token;
            $this->expirationTime = time() + $response->expires_in;
            $this->scope = isset($response->scope) ? $response->scope : $this->scope;

            return true;
        }

        return false;
    }
1219613
public function getAuthorizationInfo($authorization_code)
    {
        empty($this->component_access_token) && $this->getComponentAccessToken();
        if (empty($this->component_access_token)) {
            return false;
        }
        $data = array();
        $data['component_appid'] = $this->component_appid;
        $data['authorization_code'] = $authorization_code;
        $url = self::URL_PREFIX . self::QUERY_AUTH_URL . "?component_access_token={$this->component_access_token}";
        $result = Tools::httpPost($url, Tools::json_encode($data));
        $authorization_info = $this->_decode($result, 'authorization_info');
        if (empty($authorization_info)) {
            Tools::log("Get getAuthorizationInfo Faild. {$this->errMsg} [$this->errCode]", "ERR - {$this->authorizer_appid}");
            return false;
        }
        $authorization_info['func_info'] = $this->_parseFuncInfo($authorization_info['func_info']);
        return $authorization_info;
    }
335556
function genAuthorizationHeaderValue (options) {

    log(options.verbose,"Now generating Authorization header value ...");

    var authHeaderParams = [];

    authHeaderParams.push(createEncodedParam("oauth_consumer_key",options.oAuthConsumerKey));
    authHeaderParams.push(createEncodedParam("oauth_nonce",options.oAuthNonce));
    authHeaderParams.push(createEncodedParam("oauth_signature",options.oAuthSignature));
    authHeaderParams.push(createEncodedParam("oauth_signature_method",options.oAuthSignatureMethod));
    authHeaderParams.push(createEncodedParam("oauth_timestamp",options.oAuthTimestamp));
    authHeaderParams.push(createEncodedParam("oauth_token",options.oAuthToken));
    authHeaderParams.push(createEncodedParam("oauth_version",options.oAuthVersion));

    var authHeaderValue = "OAuth ";

    log(options.verbose,"Authorization header key/value pairs are:");

    for ( var i=0; i<authHeaderParams.length; i++ ) {
        log(options.verbose,"  "+authHeaderParams[i].key+"=\""+authHeaderParams[i].value+"\"");
        authHeaderValue += authHeaderParams[i].key+"=\""+authHeaderParams[i].value+"\"";
        if ( authHeaderParams[i+1] ) {
            authHeaderValue += ", ";
        }
    }

    log(options.verbose,"Authorization header value is: "+authHeaderValue);

    return authHeaderValue;
}
1090598
protected function __getAccessToken($storeState, $code = null, $state = null)
	{
		parse_str($this->http->get($this->getUrl('oauth2.0/token', array(
			'grant_type'	=>	'authorization_code',
			'client_id'		=>	$this->appid,
			'client_secret'	=>	$this->appSecret,
			'code'			=>	isset($code) ? $code : (isset($_GET['code']) ? $_GET['code'] : ''),
			'state'			=>	isset($state) ? $state : (isset($_GET['state']) ? $_GET['state'] : ''),
			'redirect_uri'	=>	$this->getRedirectUri(),
		)))->body(), $result);
		$this->result = $result;
		if(isset($this->result['code']) && 0 != $this->result['code'])
		{
			throw new ApiException($this->result['msg'], $this->result['code']);
		}
		else
		{
			return $this->accessToken = $this->result['access_token'];
		}
	}
647675
function getAccessToken($oauth_verifier = FALSE)
    {
        $parameters = [];
        if (!empty($oauth_verifier)) {
            $parameters['oauth_verifier'] = $oauth_verifier;
        }
        $request = $this->oAuthRequest($this->accessTokenURL(), 'GET', $parameters);
        $token = OAuthUtil::parse_parameters($request);
        $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
        return $token;
    }
994811
public static String generateAuthorizationCode() {
        StringBuilder buf = new StringBuilder(AUTHORIZATION_CODE_LENGTH);
        SecureRandom rand = new SecureRandom();
        for (int i = 0; i < AUTHORIZATION_CODE_LENGTH; i++) {
            buf.append(allowedCharacters[rand.nextInt(allowedCharacters.length)]);
        }
        return buf.toString();
    }
720701
private String buildAuthUrl(String baseAuthUrl, GrantType grantType, OAuth2Parameters parameters) {
		StringBuilder authUrl = new StringBuilder(baseAuthUrl);
		if (grantType == GrantType.AUTHORIZATION_CODE) {
			authUrl.append('&').append("response_type").append('=').append("code");
		} else if (grantType == GrantType.IMPLICIT_GRANT) {
			authUrl.append('&').append("response_type").append('=').append("token");
		}
		for (Iterator<Entry<String, List<String>>> additionalParams = parameters.entrySet().iterator(); additionalParams.hasNext();) {
			Entry<String, List<String>> param = additionalParams.next();
			String name = formEncode(param.getKey());
			for (Iterator<String> values = param.getValue().iterator(); values.hasNext();) {
				authUrl.append('&').append(name);
				String value = values.next();
				if (StringUtils.hasLength(value)) {
					authUrl.append('=').append(formEncode(value));
				}
			}
		}
		return authUrl.toString();		
	}
153909
public function respondToAccessTokenRequest(
        ServerRequestInterface $request,
        ResponseTypeInterface $responseType,
        DateInterval $accessTokenTTL
    ) {
        // Validate request
        $client = $this->validateClient($request);
        $encryptedAuthCode = $this->getRequestParameter('code', $request, null);

        if ($encryptedAuthCode === null) {
            throw OAuthServerException::invalidRequest('code');
        }

        try {
            $authCodePayload = json_decode($this->decrypt($encryptedAuthCode));

            $this->validateAuthorizationCode($authCodePayload, $client, $request);

            $scopes = $this->scopeRepository->finalizeScopes(
                $this->validateScopes($authCodePayload->scopes),
                $this->getIdentifier(),
                $client,
                $authCodePayload->user_id
            );
        } catch (LogicException $e) {
            throw OAuthServerException::invalidRequest('code', 'Cannot decrypt the authorization code', $e);
        }

        // Validate code challenge
        if ($this->enableCodeExchangeProof === true) {
            $codeVerifier = $this->getRequestParameter('code_verifier', $request, null);

            if ($codeVerifier === null) {
                throw OAuthServerException::invalidRequest('code_verifier');
            }

            // Validate code_verifier according to RFC-7636
            // @see: https://tools.ietf.org/html/rfc7636#section-4.1
            if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeVerifier) !== 1) {
                throw OAuthServerException::invalidRequest(
                    'code_verifier',
                    'Code Verifier must follow the specifications of RFC-7636.'
                );
            }

            switch ($authCodePayload->code_challenge_method) {
                case 'plain':
                    if (hash_equals($codeVerifier, $authCodePayload->code_challenge) === false) {
                        throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.');
                    }

                    break;
                case 'S256':
                    if (
                        hash_equals(
                            strtr(rtrim(base64_encode(hash('sha256', $codeVerifier, true)), '='), '+/', '-_'),
                            $authCodePayload->code_challenge
                        ) === false
                    ) {
                        throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.');
                    }
                    // @codeCoverageIgnoreStart
                    break;
                default:
                    throw OAuthServerException::serverError(
                        sprintf(
                            'Unsupported code challenge method `%s`',
                            $authCodePayload->code_challenge_method
                        )
                    );
                // @codeCoverageIgnoreEnd
            }
        }

        // Issue and persist new access token
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $authCodePayload->user_id, $scopes);
        $this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
        $responseType->setAccessToken($accessToken);

        // Issue and persist new refresh token if given
        $refreshToken = $this->issueRefreshToken($accessToken);

        if ($refreshToken !== null) {
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
            $responseType->setRefreshToken($refreshToken);
        }

        // Revoke used auth code
        $this->authCodeRepository->revokeAuthCode($authCodePayload->auth_code_id);

        return $responseType;
    }
998
protected function generateAuthorizationCode()
    {
        $tokenLen = 40;
        if (function_exists('random_bytes')) {
            $randomData = random_bytes(100);
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
            $randomData = openssl_random_pseudo_bytes(100);
        } elseif (function_exists('mcrypt_create_iv')) {
            $randomData = mcrypt_create_iv(100, MCRYPT_DEV_URANDOM);
        } elseif (@file_exists('/dev/urandom')) { // Get 100 bytes of random data
            $randomData = file_get_contents('/dev/urandom', false, null, 0, 100) . uniqid(mt_rand(), true);
        } else {
            $randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
        }

        return substr(hash('sha512', $randomData), 0, $tokenLen);
    }
1339223
public function getOauth2AccessToken($code, $grantType = 'authorization_code')
    {
        $result = $this->httpGet(self::WECHAT_OAUTH2_ACCESS_TOKEN_URL . http_build_query([
            'appid' => $this->appId,
            'secret' => $this->appSecret,
            'code' => $code,
            'grant_type' => $grantType
        ]));
        return isset($result['errmsg']) ? false : $result;
    }