0

Final Class Yiisoft\Yii\AuthClient\Client\TikTok

InheritanceYiisoft\Yii\AuthClient\Client\TikTok » Yiisoft\Yii\AuthClient\OAuth2 » Yiisoft\Yii\AuthClient\OAuth » Yiisoft\Yii\AuthClient\AuthClient
ImplementsYiisoft\Yii\AuthClient\AuthClientInterface, Yiisoft\Yii\AuthClient\OAuth2Interface, Yiisoft\Yii\AuthClient\OAuthInterface

Protected Properties

Hide inherited properties

Property Type Description Defined By
$accessToken array|Yiisoft\Yii\AuthClient\OAuthToken|null Access token instance or its array configuration. Yiisoft\Yii\AuthClient\OAuth
$authParams array Additional auth GET params, merged into every {@see \Yiisoft\Yii\AuthClient\buildAuthUrl()} call. Yiisoft\Yii\AuthClient\OAuth2
$authUrl string Yiisoft\Yii\AuthClient\Client\TikTok
$autoRefreshAccessToken boolean Whether to automatically perform 'refresh access token' request on expired access token. Yiisoft\Yii\AuthClient\OAuth
$clientId string OAuth client ID. Yiisoft\Yii\AuthClient\OAuth2
$clientSecret string OAuth client secret. Yiisoft\Yii\AuthClient\OAuth2
$endpoint string Yiisoft\Yii\AuthClient\Client\TikTok
$environment string Environment identifier (e.g. 'dev' or 'prod'), for providers whose endpoint URLs differ by environment. Yiisoft\Yii\AuthClient\OAuth2
$factory \Yiisoft\Factory\Factory Yiisoft\Yii\AuthClient\OAuth2
$httpClient \Psr\Http\Client\ClientInterface Yiisoft\Yii\AuthClient\AuthClient
$name string Custom name, set from the config array key. Yiisoft\Yii\AuthClient\AuthClient
$normalizeUserAttributeMap array Map used to normalize user attributes fetched from external auth service in format: normalizedAttributeName => sourceSpecification 'sourceSpecification' can be: - string, raw attribute name - array, pass to raw attribute value - callable, PHP callback, which should accept array of raw attributes and return normalized value. Yiisoft\Yii\AuthClient\AuthClient
$requestFactory \Psr\Http\Message\RequestFactoryInterface Yiisoft\Yii\AuthClient\AuthClient
$returnUrl string Yiisoft\Yii\AuthClient\OAuth2
$scope string String auth request scope. Yiisoft\Yii\AuthClient\OAuth
$session \Yiisoft\Session\SessionInterface Yiisoft\Yii\AuthClient\OAuth2
$title string Custom title, overrides the class default if set. Yiisoft\Yii\AuthClient\AuthClient
$tokenUrl string Yiisoft\Yii\AuthClient\Client\TikTok
$validateAuthState boolean Whether to use and validate auth 'state' parameter in authentication flow. Yiisoft\Yii\AuthClient\OAuth2
$viewOptions array View options in format: optionName => optionValue Yiisoft\Yii\AuthClient\AuthClient

Public Methods

Hide inherited methods

Method Description Defined By
__construct() BaseOAuth constructor. Yiisoft\Yii\AuthClient\OAuth2
api() Performs request to the OAuth API returning response data. Yiisoft\Yii\AuthClient\OAuth
applyAccessTokenToRequest() Yiisoft\Yii\AuthClient\OAuth2
beforeApiRequestSend() Yiisoft\Yii\AuthClient\OAuth
buildAuthUrl() Composes user authorization URL. Yiisoft\Yii\AuthClient\OAuth2
createApiRequest() Creates an HTTP request for the API call. Yiisoft\Yii\AuthClient\OAuth
createRequest() Yiisoft\Yii\AuthClient\AuthClient
fetchAccessToken() Fetches access token from authorization code. Yiisoft\Yii\AuthClient\OAuth2
fetchAccessTokenWithCodeVerifier() Note: This function will be adapted later to accomodate the 'confidential client'. Yiisoft\Yii\AuthClient\OAuth2
getAccessToken() Yiisoft\Yii\AuthClient\OAuth
getAuthParams() Yiisoft\Yii\AuthClient\OAuth2
getClientId() Yiisoft\Yii\AuthClient\OAuth2
getClientSecret() Yiisoft\Yii\AuthClient\OAuth2
getCurrentUserJsonArray() Yiisoft\Yii\AuthClient\Client\TikTok
getLogo() Yiisoft\Yii\AuthClient\OAuth2
getName() Yiisoft\Yii\AuthClient\Client\TikTok
getNormalizeUserAttributeMap() Yiisoft\Yii\AuthClient\AuthClient
getOauth2ReturnUrl() Yiisoft\Yii\AuthClient\OAuth2
getRequestFactory() Yiisoft\Yii\AuthClient\AuthClient
getReturnUrl() Yiisoft\Yii\AuthClient\OAuth
getScope() Yiisoft\Yii\AuthClient\OAuth
getSessionAuthState() Compare a callback query parameter 'state' with the saved Auth Client's 'authState' parameter in order to prevent CSRF attacks Yiisoft\Yii\AuthClient\OAuth2
getTitle() Yiisoft\Yii\AuthClient\Client\TikTok
getTokenUrl() Yiisoft\Yii\AuthClient\OAuth2
getUserAttributes() Returns the authenticated user's attributes, as fetched by {@see initUserAttributes()} and normalized according to {@see normalizeUserAttributeMap}. Yiisoft\Yii\AuthClient\AuthClient
getViewOptions() Yiisoft\Yii\AuthClient\AuthClient
getYiisoftFactory() Yiisoft\Yii\AuthClient\OAuth
refreshAccessToken() Gets new auth token to replace expired one. Yiisoft\Yii\AuthClient\OAuth2
setAccessToken() Sets access token to be used. Yiisoft\Yii\AuthClient\OAuth
setAuthParams() Yiisoft\Yii\AuthClient\OAuth2
setAuthUrl() Yiisoft\Yii\AuthClient\OAuth
setClientId() Yiisoft\Yii\AuthClient\OAuth2
setClientSecret() Yiisoft\Yii\AuthClient\OAuth2
setEnvironment() Yiisoft\Yii\AuthClient\OAuth2
setLogo() Yiisoft\Yii\AuthClient\OAuth2
setName() Yiisoft\Yii\AuthClient\AuthClient
setOauth2ReturnUrl() Yiisoft\Yii\AuthClient\OAuth2
setRequestFactory() Yiisoft\Yii\AuthClient\AuthClient
setReturnUrl() Yiisoft\Yii\AuthClient\OAuth
setScope() Yiisoft\Yii\AuthClient\OAuth
setTitle() Yiisoft\Yii\AuthClient\AuthClient
setTokenUrl() Yiisoft\Yii\AuthClient\OAuth2
setYiisoftFactory() Yiisoft\Yii\AuthClient\OAuth
withValidateAuthState() Yiisoft\Yii\AuthClient\OAuth2
withoutValidateAuthState() Yiisoft\Yii\AuthClient\OAuth2

Protected Methods

Hide inherited methods

Method Description Defined By
applyClientCredentialsToRequest() Applies client credentials (e.g. {@see clientId} and {@see clientSecret}) to the HTTP request instance. Yiisoft\Yii\AuthClient\OAuth2
createToken() Creates token from its configuration. Yiisoft\Yii\AuthClient\OAuth2
createTokenRequest() Builds a POST request to {@see tokenUrl} with $params as an application/x-www-form-urlencoded body. RFC 6749 ยง4.1.3 requires token-endpoint parameters in the request body, not the URI query string - a strict provider like Google rejects a query-string-only request outright (with no usable access_token in its error response), while a lenient one like GitHub's legacy endpoint happens to tolerate it. {@see applyClientCredentialsToRequest()} is expected to append further params to this same body afterward, not build a request of its own. Yiisoft\Yii\AuthClient\OAuth2
defaultNormalizeUserAttributeMap() Returns the default {@see normalizeUserAttributeMap} value. Yiisoft\Yii\AuthClient\AuthClient
defaultReturnUrl() Composes default {@see returnUrl} value. Yiisoft\Yii\AuthClient\OAuth2
defaultViewOptions() Returns the default {@see viewOptions} value. Yiisoft\Yii\AuthClient\AuthClient
fetchCurrentUserJsonArray() Fetches current user data as JSON array from the given endpoint, authenticating the request with the access token as an Authorization header. Yiisoft\Yii\AuthClient\OAuth2
generateAuthState() Generates the auth state value. Yiisoft\Yii\AuthClient\OAuth2
generateAuthStateBaseString() Builds the seed string used by {@see generateAuthState()}. Extracted into its own method so the seed's composition can be tested directly, since the final hashed/uniqid()-mixed auth state value is opaque and can't reveal how its input was assembled. Yiisoft\Yii\AuthClient\OAuth2
getDefaultScope() Yiisoft\Yii\AuthClient\Client\TikTok
getState() Returns persistent state value. Yiisoft\Yii\AuthClient\AuthClient
getStateKeyPrefix() Returns session key prefix, which is used to store internal states. Yiisoft\Yii\AuthClient\AuthClient
initUserAttributes() Yiisoft\Yii\AuthClient\Client\TikTok
removeState() Removes persistent state value. Yiisoft\Yii\AuthClient\AuthClient
restoreAccessToken() Restores access token. Yiisoft\Yii\AuthClient\OAuth
saveAccessToken() Saves token as persistent state. Yiisoft\Yii\AuthClient\OAuth
sendRequest() Yiisoft\Yii\AuthClient\AuthClient
setState() Sets persistent state. Yiisoft\Yii\AuthClient\AuthClient

Property Details

Hide inherited properties

$authUrl protected property
protected string $authUrl 'https://www.tiktok.com/v2/auth/authorize/'
$endpoint protected property
protected string $endpoint 'https://open.tiktokapis.com/v2/user/info/'
$tokenUrl protected property
protected string $tokenUrl 'https://open.tiktokapis.com/v2/oauth/token/'

Method Details

Hide inherited methods

__construct() public method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::__construct()

BaseOAuth constructor.

public mixed __construct ( \Psr\Http\Client\ClientInterface $httpClient, \Psr\Http\Message\RequestFactoryInterface $requestFactory, Yiisoft\Yii\AuthClient\StateStorage\StateStorageInterface $stateStorage, \Yiisoft\Factory\Factory $factory, \Yiisoft\Session\SessionInterface $session )
$httpClient \Psr\Http\Client\ClientInterface
$requestFactory \Psr\Http\Message\RequestFactoryInterface
$stateStorage Yiisoft\Yii\AuthClient\StateStorage\StateStorageInterface
$factory \Yiisoft\Factory\Factory
$session \Yiisoft\Session\SessionInterface

                public function __construct(
    ClientInterface $httpClient,
    RequestFactoryInterface $requestFactory,
    StateStorageInterface $stateStorage,
    protected YiisoftFactory $factory,
    protected SessionInterface $session,
) {
    parent::__construct($httpClient, $requestFactory, $stateStorage, $this->factory);
}

            
api() public method

Defined in: Yiisoft\Yii\AuthClient\OAuth::api()

Performs request to the OAuth API returning response data.

You may use {@see \Yiisoft\Yii\AuthClient\createApiRequest()} method instead, gaining more control over request execution.

See also createApiRequest().

public array api ( string $apiSubUrl, string $method 'GET', array|string $data = [], array $headers = [] )
$apiSubUrl string

API sub URL, which will be append to {@see \Yiisoft\Yii\AuthClient\apiBaseUrl}, or absolute API URL.

$method string

Request method.

$data array|string

Request data or content.

$headers array

Additional request headers.

return array

API response data.

throws Exception

                public function api($apiSubUrl, $method = 'GET', $data = [], $headers = []): array
{
    $request = $this->createApiRequest($method, $apiSubUrl);
    $request = RequestUtil::addHeaders($request, $headers);
    if (!empty($data)) {
        if (is_array($data)) {
            $request = RequestUtil::addParams($request, $data);
        } else {
            $request->getBody()->write($data);
        }
    }
    $request = $this->beforeApiRequestSend($request);
    $response = $this->sendRequest($request);
    if ($response->getStatusCode() !== 200) {
        throw new InvalidResponseException(
            $response,
            'Request failed with code: ' . $response->getStatusCode() . ', message: ' . $response->getBody(),
        );
    }
    return (array) Json::decode($response->getBody()->getContents());
}

            
applyAccessTokenToRequest() public method
public \Psr\Http\Message\RequestInterface applyAccessTokenToRequest ( \Psr\Http\Message\RequestInterface $request, Yiisoft\Yii\AuthClient\OAuthToken $accessToken )
$request \Psr\Http\Message\RequestInterface
$accessToken Yiisoft\Yii\AuthClient\OAuthToken

                public function applyAccessTokenToRequest(RequestInterface $request, OAuthToken $accessToken): RequestInterface
{
    return RequestUtil::addParams(
        $request,
        [
            'access_token' => $accessToken->getToken(),
        ],
    );
}

            
applyClientCredentialsToRequest() protected method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::applyClientCredentialsToRequest()

Applies client credentials (e.g. {@see clientId} and {@see clientSecret}) to the HTTP request instance.

This method should be invoked before sending any HTTP request, which requires client credentials.

Assumes $request already carries a createTokenRequest()-built application/x-www-form-urlencoded body - the credentials are appended to that body, not the URI query string, matching how every caller of this method builds its request. Overrides (e.g. OpenIdConnect, which may instead add an Authorization header for client_secret_basic) aren't bound by that assumption.

protected \Psr\Http\Message\RequestInterface applyClientCredentialsToRequest ( \Psr\Http\Message\RequestInterface $request )
$request \Psr\Http\Message\RequestInterface

HTTP request instance.

                protected function applyClientCredentialsToRequest(RequestInterface $request): RequestInterface
{
    $request->getBody()->write('&' . http_build_query(
        [
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecret,
        ],
        arg_separator: '&',
        encoding_type: PHP_QUERY_RFC3986,
    ));
    return $request;
}

            
beforeApiRequestSend() public method
public \Psr\Http\Message\RequestInterface beforeApiRequestSend ( \Psr\Http\Message\RequestInterface $request )
$request \Psr\Http\Message\RequestInterface

                public function beforeApiRequestSend(RequestInterface $request): RequestInterface
{
    $accessToken = $this->getAccessToken();
    if (!is_object($accessToken) || !$accessToken->getIsValid()) {
        throw new Exception('Invalid access token.');
    }
    return $this->applyAccessTokenToRequest($request, $accessToken);
}

            
buildAuthUrl() public method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::buildAuthUrl()

Composes user authorization URL.

public string buildAuthUrl ( \Psr\Http\Message\ServerRequestInterface $incomingRequest, array $params = [] )
$incomingRequest \Psr\Http\Message\ServerRequestInterface
$params array

Additional auth GET params.

return string

Authorization URL.

                public function buildAuthUrl(ServerRequestInterface $incomingRequest, array $params = []): string
{
    $defaultParams = [
        'client_id' => $this->clientId,
        'response_type' => 'code',
        'redirect_uri' => $this->getOauth2ReturnUrl(),
        'xoauth_displayname' => $incomingRequest->getAttribute(AuthAction::AUTH_NAME),
    ];
    if (!empty($this->getScope())) {
        $defaultParams['scope'] = $this->getScope();
    }
    if ($this->validateAuthState) {
        $authState = $this->generateAuthState();
        $this->setState('authState', $authState);
        $defaultParams['state'] = $authState;
    }
    return RequestUtil::composeUrl($this->authUrl, array_merge($defaultParams, $this->authParams, $params));
}

            
createApiRequest() public method

Defined in: Yiisoft\Yii\AuthClient\OAuth::createApiRequest()

Creates an HTTP request for the API call.

The created request will be automatically processed adding access token parameters and signature before sending. You may use {@see \Yiisoft\Yii\AuthClient\createRequest()} to gain full control over request composition and execution.

See also createRequest().

public \Psr\Http\Message\RequestInterface createApiRequest ( string $method, string $uri )
$method string
$uri string
return \Psr\Http\Message\RequestInterface

HTTP request instance.

                public function createApiRequest(string $method, string $uri): RequestInterface
{
    return $this->createRequest($method, $this->endpoint . $uri);
}

            
createRequest() public method
public \Psr\Http\Message\RequestInterface createRequest ( string $method, string $uri )
$method string
$uri string

                public function createRequest(string $method, string $uri): RequestInterface
{
    return $this->requestFactory->createRequest($method, $uri);
}

            
createToken() protected method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::createToken()

Creates token from its configuration.

protected Yiisoft\Yii\AuthClient\OAuthToken createToken ( array $tokenConfig = [] )
$tokenConfig array

Token configuration.

return Yiisoft\Yii\AuthClient\OAuthToken

Token instance.

                protected function createToken(array $tokenConfig = []): OAuthToken
{
    $tokenConfig['tokenParamKey'] = 'access_token';
    return parent::createToken($tokenConfig);
}

            
createTokenRequest() protected method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::createTokenRequest()

Builds a POST request to {@see tokenUrl} with $params as an application/x-www-form-urlencoded body. RFC 6749 ยง4.1.3 requires token-endpoint parameters in the request body, not the URI query string - a strict provider like Google rejects a query-string-only request outright (with no usable access_token in its error response), while a lenient one like GitHub's legacy endpoint happens to tolerate it. {@see applyClientCredentialsToRequest()} is expected to append further params to this same body afterward, not build a request of its own.

protected \Psr\Http\Message\RequestInterface createTokenRequest ( array $params )
$params array

                protected function createTokenRequest(array $params): RequestInterface
{
    $request = $this->createRequest('POST', $this->tokenUrl)
        ->withHeader('Content-Type', 'application/x-www-form-urlencoded');
    $request->getBody()->write(http_build_query($params, arg_separator: '&', encoding_type: PHP_QUERY_RFC3986));
    return $request;
}

            
defaultNormalizeUserAttributeMap() protected method

Defined in: Yiisoft\Yii\AuthClient\AuthClient::defaultNormalizeUserAttributeMap()

Returns the default {@see normalizeUserAttributeMap} value.

Particular client may override this method in order to provide specific default map.

protected array defaultNormalizeUserAttributeMap ( )
return array

Normalize attribute map.

                protected function defaultNormalizeUserAttributeMap(): array
{
    return [];
}

            
defaultReturnUrl() protected method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::defaultReturnUrl()

Composes default {@see returnUrl} value.

protected string defaultReturnUrl ( \Psr\Http\Message\ServerRequestInterface $request )
$request \Psr\Http\Message\ServerRequestInterface
return string

Return URL.

                protected function defaultReturnUrl(ServerRequestInterface $request): string
{
    $params = $request->getQueryParams();
    unset($params['code'], $params['state']);
    return (string) $request->getUri()->withQuery(
        http_build_query($params, arg_separator: '&', encoding_type: PHP_QUERY_RFC3986),
    );
}

            
defaultViewOptions() protected method

Defined in: Yiisoft\Yii\AuthClient\AuthClient::defaultViewOptions()

Returns the default {@see viewOptions} value.

Particular client may override this method in order to provide specific default view options.

protected array defaultViewOptions ( )
return array

List of default {@see \Yiisoft\Yii\AuthClient\viewOptions}

                protected function defaultViewOptions(): array
{
    return [
        'popupWidth' => 860,
        'popupHeight' => 480,
    ];
}

            
fetchAccessToken() public method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::fetchAccessToken()

Fetches access token from authorization code.

public Yiisoft\Yii\AuthClient\OAuthToken fetchAccessToken ( \Psr\Http\Message\ServerRequestInterface $incomingRequest, string $authCode, array $params = [] )
$incomingRequest \Psr\Http\Message\ServerRequestInterface
$authCode string

Authorization code, usually comes at GET parameter 'code'.

$params array

Additional request params.

return Yiisoft\Yii\AuthClient\OAuthToken

Access token.

                public function fetchAccessToken(
    ServerRequestInterface $incomingRequest,
    string $authCode,
    array $params = [],
): OAuthToken {
    if ($this->validateAuthState) {
        /**
         * @var string|null $authState 'authState' is only ever written by
         * {@see buildAuthUrl()} with the string returned from {@see generateAuthState()}.
         */
        $authState = $this->getState('authState');
        $queryParams = $incomingRequest->getQueryParams();
        $bodyParams = $incomingRequest->getParsedBody();
        /**
         * @psalm-suppress MixedAssignment
         */
        $incomingState = $queryParams['state'] ?? ($bodyParams['state'] ?? null);
        if (
            !is_string($incomingState)
            || empty($authState)
            || strcmp($incomingState, $authState) !== 0
        ) {
            throw new InvalidArgumentException('Invalid auth state parameter.');
        }
        $this->removeState('authState');
    }
    $defaultParams = [
        'grant_type' => 'authorization_code',
        'code' => $authCode,
        'redirect_uri' => $this->getOauth2ReturnUrl(),
    ];
    $request = $this->createTokenRequest(array_merge($defaultParams, $params));
    $request = $this->applyClientCredentialsToRequest($request);
    $response = $this->sendRequest($request);
    $contents = $response->getBody()->getContents();
    $output = $this->parseTokenResponse($contents);
    $token = $this->createToken(['params' => $output]);
    $this->setAccessToken($token);
    return $token;
}

            
fetchAccessTokenWithCodeVerifier() public method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::fetchAccessTokenWithCodeVerifier()

Note: This function will be adapted later to accomodate the 'confidential client'.

See also https://docs.x.com/resources/fundamentals/authentication/oauth-2-0/authorization-code Used specifically for the X i.e. Twitter OAuth2.0 Authorization code with PKCE and public client i.e. client id included in request body; and NOT Confidential Client i.e. Client id not included in the request body.

public Yiisoft\Yii\AuthClient\OAuthToken fetchAccessTokenWithCodeVerifier ( \Psr\Http\Message\ServerRequestInterface $incomingRequest, string $authCode, array $params = [] )
$incomingRequest \Psr\Http\Message\ServerRequestInterface
$authCode string
$params array
throws InvalidArgumentException

                public function fetchAccessTokenWithCodeVerifier(
    ServerRequestInterface $incomingRequest,
    string $authCode,
    array $params = [],
): OAuthToken {
    if ($this->validateAuthState) {
        /**
         * @var string|null $authState 'authState' is only ever written by
         * {@see buildAuthUrl()} with the string returned from {@see generateAuthState()}.
         */
        $authState = $this->getState('authState');
        $queryParams = $incomingRequest->getQueryParams();
        $bodyParams = $incomingRequest->getParsedBody();
        /**
         * @psalm-suppress MixedAssignment
         */
        $incomingState = $queryParams['state'] ?? ($bodyParams['state'] ?? null);
        if (is_string($incomingState)) {
            if (strcmp($incomingState, (string) $authState) !== 0) {
                throw new InvalidArgumentException('Invalid auth state parameter.');
            }
        }
        if ($incomingState === null) {
            throw new InvalidArgumentException('Invalid auth state parameter.');
        }
        if (empty($authState)) {
            throw new InvalidArgumentException('Invalid auth state parameter.');
        }
        $this->removeState('authState');
    }
    $requestBody = [
        'code' => $authCode,
        'grant_type' => 'authorization_code',
        'client_id' => $this->clientId,
        'client_secret' => $this->clientSecret,
        'redirect_uri' => $params['redirect_uri'] ?? '',
        'code_verifier' => $params['code_verifier'] ?? '',
    ];
    $request = $this->requestFactory
        ->createRequest('POST', $this->tokenUrl)
        ->withHeader(Header::CONTENT_TYPE, 'application/x-www-form-urlencoded');
    $request->getBody()->write(
        http_build_query($requestBody, arg_separator: '&', encoding_type: PHP_QUERY_RFC3986),
    );
    try {
        $response = $this->httpClient->sendRequest($request);
        $body = $response->getBody()->getContents();
        $output = (array) Json::decode($body);
    } catch (Throwable) {
        $output = [];
    }
    $token = $this->createToken(['params' => $output]);
    $this->setAccessToken($token);
    return $token;
}

            
fetchCurrentUserJsonArray() protected method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::fetchCurrentUserJsonArray()

Fetches current user data as JSON array from the given endpoint, authenticating the request with the access token as an Authorization header.

protected array fetchCurrentUserJsonArray ( Yiisoft\Yii\AuthClient\OAuthToken $token, string $url, array $headers = [], string $authScheme 'Bearer' )
$token Yiisoft\Yii\AuthClient\OAuthToken

Access token, whose access_token param is used for authentication.

$url string

Endpoint URL to fetch user data from.

$headers array

Additional request headers, merged over the default Authorization header.

$authScheme string

Authorization header scheme, e.g. Bearer or OAuth.

return array

Decoded user data, or an empty array if there is no access token or the request fails.

                protected function fetchCurrentUserJsonArray(
    OAuthToken $token,
    string $url,
    array $headers = [],
    string $authScheme = 'Bearer',
): array {
    $tokenString = (string) $token->getParam('access_token');
    if ($tokenString === '') {
        return [];
    }
    $request = RequestUtil::addHeaders(
        $this->createRequest('GET', $url),
        array_merge(['Authorization' => $authScheme . ' ' . $tokenString], $headers),
    );
    if ($request->getHeaderLine('User-Agent') === '') {
        $request = $request->withHeader('User-Agent', 'yiisoft/yii-auth-client');
    }
    try {
        $body = $this->sendRequest($request)->getBody()->getContents();
    } catch (Throwable) {
        return [];
    }
    return $body === '' ? [] : (array) Json::decode($body);
}

            
generateAuthState() protected method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::generateAuthState()

Generates the auth state value.

protected string generateAuthState ( )
return string

Auth state value.

                protected function generateAuthState(): string
{
    return hash('sha256', uniqid($this->generateAuthStateBaseString(), true));
}

            
generateAuthStateBaseString() protected method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::generateAuthStateBaseString()

Builds the seed string used by {@see generateAuthState()}. Extracted into its own method so the seed's composition can be tested directly, since the final hashed/uniqid()-mixed auth state value is opaque and can't reveal how its input was assembled.

protected string generateAuthStateBaseString ( )
return string

Auth state seed.

                protected function generateAuthStateBaseString(): string
{
    $baseString = static::class . '-' . time();
    $sessionId = $this->session->getId();
    if (null !== $sessionId) {
        if ($this->session->isActive()) {
            $baseString .= '-' . $sessionId;
        }
    }
    return $baseString;
}

            
getAccessToken() public method
public Yiisoft\Yii\AuthClient\OAuthToken|null getAccessToken ( )
return Yiisoft\Yii\AuthClient\OAuthToken|null

Auth token instance.

                public function getAccessToken(): ?OAuthToken
{
    if (!is_object($this->accessToken)) {
        $this->accessToken = $this->restoreAccessToken();
    }
    return $this->accessToken;
}

            
getAuthParams() public method
public array getAuthParams ( )

                public function getAuthParams(): array
{
    return $this->authParams;
}

            
getClientId() public method
public string getClientId ( )

                public function getClientId(): string
{
    return $this->clientId;
}

            
getClientSecret() public method
public string getClientSecret ( )

                public function getClientSecret(): string
{
    return $this->clientSecret;
}

            
getCurrentUserJsonArray() public method

public array getCurrentUserJsonArray ( Yiisoft\Yii\AuthClient\OAuthToken $oauthToken )
$oauthToken Yiisoft\Yii\AuthClient\OAuthToken

                public function getCurrentUserJsonArray(OAuthToken $oauthToken): array
{
    return $this->fetchCurrentUserJsonArray(
        $oauthToken,
        $this->endpoint . '?fields=open_id,display_name,avatar_url',
    );
}

            
getDefaultScope() protected method

protected string getDefaultScope ( )

                protected function getDefaultScope(): string
{
    return 'user.info.profile';
}

            
getLogo() public method
public ?string getLogo ( )

getName() public method

public string getName ( )

                public function getName(): string
{
    return $this->name ?: 'tiktok';
}

            
getNormalizeUserAttributeMap() public method
public array getNormalizeUserAttributeMap ( )
return array

Normalize user attribute map.

                public function getNormalizeUserAttributeMap(): array
{
    if (empty($this->normalizeUserAttributeMap)) {
        $this->normalizeUserAttributeMap = $this->defaultNormalizeUserAttributeMap();
    }
    return $this->normalizeUserAttributeMap;
}

            
getOauth2ReturnUrl() public method
public string getOauth2ReturnUrl ( )

                public function getOauth2ReturnUrl(): string
{
    return $this->returnUrl;
}

            
getRequestFactory() public method
public \Psr\Http\Message\RequestFactoryInterface getRequestFactory ( )

                public function getRequestFactory(): RequestFactoryInterface
{
    return $this->requestFactory;
}

            
getReturnUrl() public method
public string getReturnUrl ( \Psr\Http\Message\ServerRequestInterface $request )
$request \Psr\Http\Message\ServerRequestInterface
return string

Return URL.

                public function getReturnUrl(ServerRequestInterface $request): string
{
    if ($this->returnUrl === '') {
        $this->returnUrl = $this->defaultReturnUrl($request);
    }
    return $this->returnUrl;
}

            
getScope() public method
public string getScope ( )

                public function getScope(): string
{
    if ($this->scope === null) {
        return $this->getDefaultScope();
    }
    return $this->scope;
}

            
getSessionAuthState() public method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::getSessionAuthState()

Compare a callback query parameter 'state' with the saved Auth Client's 'authState' parameter in order to prevent CSRF attacks

Use: Typically used in a AuthController's callback function specifically for an Identity Provider e.g. Facebook

public mixed getSessionAuthState ( )

                public function getSessionAuthState(): mixed
{
    /**
     * @see src\AuthClient protected function getState('authState')
     */
    return $this->getState('authState');
}

            
getState() protected method

Defined in: Yiisoft\Yii\AuthClient\AuthClient::getState()

Returns persistent state value.

protected mixed getState ( string $key )
$key string

State key.

return mixed

State value.

                protected function getState(string $key): mixed
{
    return $this->stateStorage->get($this->getStateKeyPrefix() . $key);
}

            
getStateKeyPrefix() protected method

Defined in: Yiisoft\Yii\AuthClient\AuthClient::getStateKeyPrefix()

Returns session key prefix, which is used to store internal states.

protected string getStateKeyPrefix ( )
return string

Session key prefix.

                protected function getStateKeyPrefix(): string
{
    return static::class . '_' . $this->getName() . '_';
}

            
getTitle() public method

public string getTitle ( )

                public function getTitle(): string
{
    return $this->title ?: 'TikTok';
}

            
getTokenUrl() public method
public string getTokenUrl ( )

                public function getTokenUrl(): string
{
    return $this->tokenUrl;
}

            
getUserAttributes() public method

Defined in: Yiisoft\Yii\AuthClient\AuthClient::getUserAttributes()

Returns the authenticated user's attributes, as fetched by {@see initUserAttributes()} and normalized according to {@see normalizeUserAttributeMap}.

public array getUserAttributes ( )
return array

User attributes.

                public function getUserAttributes(): array
{
    $attributes = $this->initUserAttributes();
    $normalizeMap = $this->getNormalizeUserAttributeMap();
    return array_merge($attributes, $this->normalizeUserAttributes($attributes, $normalizeMap));
}

            
getViewOptions() public method
public array getViewOptions ( )
return array

View options in format: optionName => optionValue

                public function getViewOptions(): array
{
    if (empty($this->viewOptions)) {
        $this->viewOptions = $this->defaultViewOptions();
    }
    return $this->viewOptions;
}

            
getYiisoftFactory() public method
public \Yiisoft\Factory\Factory getYiisoftFactory ( )

                public function getYiisoftFactory(): YiisoftFactory
{
    return $this->factory;
}

            
initUserAttributes() protected method

protected array initUserAttributes ( )

                protected function initUserAttributes(): array
{
    $token = $this->getAccessToken();
    if ($token instanceof OAuthToken) {
        return $this->getCurrentUserJsonArray($token);
    }
    return [];
}

            
refreshAccessToken() public method

Defined in: Yiisoft\Yii\AuthClient\OAuth2::refreshAccessToken()

Gets new auth token to replace expired one.

See also https://developers.google.com/oauthplayground.

public Yiisoft\Yii\AuthClient\OAuthToken refreshAccessToken ( Yiisoft\Yii\AuthClient\OAuthToken $token )
$token Yiisoft\Yii\AuthClient\OAuthToken

Expired auth token.

return Yiisoft\Yii\AuthClient\OAuthToken

New auth token.

                public function refreshAccessToken(OAuthToken $token): OAuthToken
{
    $params = [
        'grant_type' => 'refresh_token',
    ];
    $params = array_merge($token->getParams(), $params);
    $request = $this->createTokenRequest($params);
    $request = $this->applyClientCredentialsToRequest($request);
    $response = $this->sendRequest($request);
    $contents = $response->getBody()->getContents();
    $output = $this->parseTokenResponse($contents);
    return $this->createToken(['params' => $output]);
}

            
removeState() protected method

Defined in: Yiisoft\Yii\AuthClient\AuthClient::removeState()

Removes persistent state value.

protected void removeState ( string $key )
$key string

State key.

                protected function removeState(string $key): void
{
    $this->stateStorage->remove($this->getStateKeyPrefix() . $key);
}

            
restoreAccessToken() protected method

Defined in: Yiisoft\Yii\AuthClient\OAuth::restoreAccessToken()

Restores access token.

protected Yiisoft\Yii\AuthClient\OAuthToken|null restoreAccessToken ( )

                protected function restoreAccessToken(): ?OAuthToken
{
    if (($token = $this->getState('token')) instanceof OAuthToken) {
        if ($token->getIsExpired() && $this->autoRefreshAccessToken) {
            return $this->refreshAccessToken($token);
        }
        return $token;
    }
    return null;
}

            
saveAccessToken() protected method

Defined in: Yiisoft\Yii\AuthClient\OAuth::saveAccessToken()

Saves token as persistent state.

protected $this saveAccessToken ( Yiisoft\Yii\AuthClient\OAuthToken|null $token null )
$token Yiisoft\Yii\AuthClient\OAuthToken|null

Auth token to be saved.

return $this

The object itself.

                protected function saveAccessToken(?OAuthToken $token = null): self
{
    return $this->setState('token', $token);
}

            
sendRequest() protected method
protected \Psr\Http\Message\ResponseInterface sendRequest ( \Psr\Http\Message\RequestInterface $request )
$request \Psr\Http\Message\RequestInterface

                protected function sendRequest(RequestInterface $request): ResponseInterface
{
    return $this->httpClient->sendRequest($request);
}

            
setAccessToken() public method

Defined in: Yiisoft\Yii\AuthClient\OAuth::setAccessToken()

Sets access token to be used.

public void setAccessToken ( array|Yiisoft\Yii\AuthClient\OAuthToken $token )
$token array|Yiisoft\Yii\AuthClient\OAuthToken

Access token or its configuration.

                public function setAccessToken(array|OAuthToken $token): void
{
    if (is_array($token) && !empty($token)) {
        $newToken = $this->createToken($token);
        $this->accessToken = $newToken;
        $this->saveAccessToken($newToken);
    }
    if ($token instanceof OAuthToken) {
        $this->accessToken = $token;
        $this->saveAccessToken($token);
    }
}

            
setAuthParams() public method
public void setAuthParams ( array $authParams )
$authParams array

                public function setAuthParams(array $authParams): void
{
    $this->authParams = $authParams;
}

            
setAuthUrl() public method
public void setAuthUrl ( string $authUrl )
$authUrl string

                public function setAuthUrl(string $authUrl): void
{
    $this->authUrl = $authUrl;
}

            
setClientId() public method
public void setClientId ( string $clientId )
$clientId string

                public function setClientId(string $clientId): void
{
    $this->clientId = $clientId;
}

            
setClientSecret() public method
public void setClientSecret ( string $clientSecret )
$clientSecret string

                public function setClientSecret(string $clientSecret): void
{
    $this->clientSecret = $clientSecret;
}

            
setEnvironment() public method
public void setEnvironment ( string $devOrProd )
$devOrProd string

                public function setEnvironment(string $devOrProd): void
{
    $this->environment = $devOrProd;
}

            
setLogo() public method
public void setLogo ( ?string $logo )
$logo ?string

setName() public method
public void setName ( string $name )
$name string

                public function setName(string $name): void
{
    $this->name = $name;
}

            
setOauth2ReturnUrl() public method
public void setOauth2ReturnUrl ( string $returnUrl )
$returnUrl string

                public function setOauth2ReturnUrl(string $returnUrl): void
{
    $this->returnUrl = $returnUrl;
}

            
setRequestFactory() public method
public void setRequestFactory ( \Psr\Http\Message\RequestFactoryInterface $requestFactory )
$requestFactory \Psr\Http\Message\RequestFactoryInterface

                public function setRequestFactory(RequestFactoryInterface $requestFactory): void
{
    $this->requestFactory = $requestFactory;
}

            
setReturnUrl() public method
public void setReturnUrl ( string $returnUrl )
$returnUrl string

Return URL

                public function setReturnUrl(string $returnUrl): void
{
    $this->returnUrl = $returnUrl;
}

            
setScope() public method
public void setScope ( string $scope )
$scope string

Auth request scope, overriding {@see \Yiisoft\Yii\AuthClient\getDefaultScope()}.

                public function setScope(string $scope): void
{
    $this->scope = $scope;
}

            
setState() protected method

Defined in: Yiisoft\Yii\AuthClient\AuthClient::setState()

Sets persistent state.

protected $this setState ( string $key, mixed $value )
$key string

State key.

$value mixed

State value

return $this

The object itself

                protected function setState(string $key, $value): self
{
    $this->stateStorage->set($this->getStateKeyPrefix() . $key, $value);
    return $this;
}

            
setTitle() public method
public void setTitle ( string $title )
$title string

                public function setTitle(string $title): void
{
    $this->title = $title;
}

            
setTokenUrl() public method
public void setTokenUrl ( string $tokenUrl )
$tokenUrl string

                public function setTokenUrl(string $tokenUrl): void
{
    $this->tokenUrl = $tokenUrl;
}

            
setYiisoftFactory() public method
public void setYiisoftFactory ( \Yiisoft\Factory\Factory $factory )
$factory \Yiisoft\Factory\Factory

                public function setYiisoftFactory(YiisoftFactory $factory): void
{
    $this->factory = $factory;
}

            
withValidateAuthState() public method
public self withValidateAuthState ( )

                public function withValidateAuthState(): self
{
    $new = clone $this;
    $new->validateAuthState = true;
    return $new;
}

            
withoutValidateAuthState() public method
public self withoutValidateAuthState ( )

                public function withoutValidateAuthState(): self
{
    $new = clone $this;
    $new->validateAuthState = false;
    return $new;
}