0 follower

Abstract Class Yiisoft\Yii\AuthClient\OAuth

InheritanceYiisoft\Yii\AuthClient\OAuth » Yiisoft\Yii\AuthClient\AuthClient
ImplementsYiisoft\Yii\AuthClient\AuthClientInterface
SubclassesYiisoft\Yii\AuthClient\Client\Facebook, Yiisoft\Yii\AuthClient\Client\GitHub, Yiisoft\Yii\AuthClient\Client\Google, Yiisoft\Yii\AuthClient\Client\LinkedIn, Yiisoft\Yii\AuthClient\Client\MicrosoftOnline, Yiisoft\Yii\AuthClient\Client\OpenIdConnect, Yiisoft\Yii\AuthClient\Client\TikTok, Yiisoft\Yii\AuthClient\Client\VKontakte, Yiisoft\Yii\AuthClient\Client\X, Yiisoft\Yii\AuthClient\Client\Yandex, Yiisoft\Yii\AuthClient\OAuth2

BaseOAuth is a base class for the OAuth clients.

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
$authUrl string Authorize URL. Yiisoft\Yii\AuthClient\OAuth
$autoRefreshAccessToken boolean Whether to automatically perform 'refresh access token' request on expired access token. Yiisoft\Yii\AuthClient\OAuth
$endpoint string API base URL. Yiisoft\Yii\AuthClient\OAuth
$factory \Yiisoft\Factory\Factory Yiisoft\Yii\AuthClient\OAuth
$httpClient \Psr\Http\Client\ClientInterface 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 URL, which user will be redirected after authentication at the OAuth provider web site. Yiisoft\Yii\AuthClient\OAuth
$scope string String auth request scope. Yiisoft\Yii\AuthClient\OAuth
$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\OAuth
api() Performs request to the OAuth API returning response data. Yiisoft\Yii\AuthClient\OAuth
applyAccessTokenToRequest() Applies access token to the HTTP request instance. Yiisoft\Yii\AuthClient\OAuth
beforeApiRequestSend() Yiisoft\Yii\AuthClient\OAuth
buildAuthUrl() Yiisoft\Yii\AuthClient\AuthClient
createApiRequest() Creates an HTTP request for the API call. Yiisoft\Yii\AuthClient\OAuth
createRequest() Yiisoft\Yii\AuthClient\AuthClient
getAccessToken() Yiisoft\Yii\AuthClient\OAuth
getButtonClass() Yiisoft\Yii\AuthClient\AuthClientInterface
getClientId() The Client id is publically visible in button urls The Client secret must not be made available publically => exclude from interface Yiisoft\Yii\AuthClient\AuthClientInterface
getName() Yiisoft\Yii\AuthClient\AuthClientInterface
getNormalizeUserAttributeMap() Yiisoft\Yii\AuthClient\AuthClient
getRequestFactory() Yiisoft\Yii\AuthClient\AuthClient
getReturnUrl() Yiisoft\Yii\AuthClient\OAuth
getScope() Yiisoft\Yii\AuthClient\OAuth
getTitle() Yiisoft\Yii\AuthClient\AuthClientInterface
getViewOptions() Yiisoft\Yii\AuthClient\AuthClient
getYiisoftFactory() Yiisoft\Yii\AuthClient\OAuth
refreshAccessToken() Gets new auth token to replace expired one. Yiisoft\Yii\AuthClient\OAuth
setAccessToken() Sets access token to be used. Yiisoft\Yii\AuthClient\OAuth
setAuthUrl() Yiisoft\Yii\AuthClient\OAuth
setRequestFactory() Yiisoft\Yii\AuthClient\AuthClient
setReturnUrl() Yiisoft\Yii\AuthClient\OAuth
setYiisoftFactory() Yiisoft\Yii\AuthClient\OAuth

Property Details

Hide inherited properties

$accessToken protected property

Access token instance or its array configuration.

$authUrl protected property

Authorize URL.

protected string $authUrl null
$autoRefreshAccessToken protected property

Whether to automatically perform 'refresh access token' request on expired access token.

$endpoint protected property

API base URL. This field will be used as \Yiisoft\Yii\AuthClient\UriInterface::getPath()} value of $httpClient. Note: changing this property will take no effect after $httpClient is instantiated.

protected string $endpoint null
$factory protected property
protected \Yiisoft\Factory\Factory $factory null
$returnUrl protected property

URL, which user will be redirected after authentication at the OAuth provider web site. Note: this should be absolute URL (with http:// or https:// leading). By default current URL will be used.

protected string $returnUrl ''
$scope protected property

String auth request scope.

protected string $scope null

Method Details

Hide inherited methods

__construct() public method

BaseOAuth constructor.

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

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

            
api() public method

Performs request to the OAuth API returning response data.

You may use createApiRequest() method instead, gaining more control over request execution.

See also createApiRequest().

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

API sub URL, which will be append to \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: ' . (string)$response->getBody()
        );
    }
    return (array)Json::decode($response->getBody()->getContents());
}

            
applyAccessTokenToRequest() public abstract method

Applies access token to the HTTP request instance.

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

HTTP request instance.

$accessToken Yiisoft\Yii\AuthClient\OAuthToken

Access token instance.

                abstract public function applyAccessTokenToRequest(
    RequestInterface $request,
    OAuthToken $accessToken
): RequestInterface;

            
beforeApiRequestSend() public method

public beforeApiRequestSend( \Psr\Http\Message\RequestInterface $request ): \Psr\Http\Message\RequestInterface
$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 abstract method
public abstract buildAuthUrl( \Psr\Http\Message\ServerRequestInterface $incomingRequest, array $params ): string
$incomingRequest \Psr\Http\Message\ServerRequestInterface
$params array

                #[\Override]
abstract public function buildAuthUrl(ServerRequestInterface $incomingRequest, array $params): string;

            
createApiRequest() public method

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 createRequest() to gain full control over request composition and execution.

See also createRequest().

public createApiRequest( string $method, string $uri ): \Psr\Http\Message\RequestInterface
$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 createRequest( string $method, string $uri ): \Psr\Http\Message\RequestInterface
$method string
$uri string

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

            
createToken() protected method

Creates token from its configuration.

See also \Yiisoft\Yii\AuthClient\Yiisoft\Factory\Factory.

protected createToken( array $tokenConfig ): Yiisoft\Yii\AuthClient\OAuthToken
$tokenConfig array

Token configuration.

throws \Yiisoft\Definitions\Exception\InvalidConfigException

                protected function createToken(array $tokenConfig): OAuthToken
{
    if (!array_key_exists('class', $tokenConfig)) {
        $tokenConfig['class'] = OAuthToken::class;
    }
    return $this->factory->create($tokenConfig['class']);
}

            
defaultNormalizeUserAttributeMap() protected method

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

Returns the default $normalizeUserAttributeMap value.

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

protected defaultNormalizeUserAttributeMap( ): array
return array

Normalize attribute map.

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

            
defaultReturnUrl() protected method

Composes default $returnUrl value.

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

Return URL.

                protected function defaultReturnUrl(ServerRequestInterface $request): string
{
    return (string)$request->getUri();
}

            
defaultViewOptions() protected method

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

Returns the default $viewOptions value.

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

protected defaultViewOptions( ): array
return array

List of default $viewOptions

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

            
getAccessToken() public method

public getAccessToken( ): Yiisoft\Yii\AuthClient\OAuthToken|null
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;
}

            
getButtonClass() public abstract method
public abstract getButtonClass( ): string

                public function getButtonClass(): string;

            
getClientId() public abstract method

Defined in: Yiisoft\Yii\AuthClient\AuthClientInterface::getClientId()

The Client id is publically visible in button urls The Client secret must not be made available publically => exclude from interface

public abstract getClientId( ): string

                public function getClientId(): string;

            
getDefaultScope() protected method

protected getDefaultScope( ): string

                protected function getDefaultScope(): string
{
    return '';
}

            
getName() public abstract method
public abstract getName( ): string
return string

Service name.

                public function getName(): string;

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

Normalize user attribute map.

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

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

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

            
getReturnUrl() public method

public getReturnUrl( \Psr\Http\Message\ServerRequestInterface $request ): string
$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 getScope( ): string

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

            
getState() protected method

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

Returns persistent state value.

protected getState( string $key ): mixed
$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 getStateKeyPrefix( ): string
return string

Session key prefix.

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

            
getTitle() public abstract method
public abstract getTitle( ): string
return string

Service title.

                public function getTitle(): string;

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

View options in format: optionName => optionValue

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

            
getYiisoftFactory() public method

public getYiisoftFactory( ): \Yiisoft\Factory\Factory

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

            
refreshAccessToken() public abstract method

Gets new auth token to replace expired one.

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

Expired auth token.

return Yiisoft\Yii\AuthClient\OAuthToken

New auth token.

                abstract public function refreshAccessToken(OAuthToken $token): OAuthToken;

            
removeState() protected method

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

Removes persistent state value.

protected removeState( string $key ): void
$key string

State key.

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

            
restoreAccessToken() protected method

Restores access token.

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

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

            
saveAccessToken() protected method

Saves token as persistent state.

protected saveAccessToken( Yiisoft\Yii\AuthClient\OAuthToken|null $token null ): $this
$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 sendRequest( \Psr\Http\Message\RequestInterface $request ): \Psr\Http\Message\ResponseInterface
$request \Psr\Http\Message\RequestInterface

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

            
setAccessToken() public method

Sets access token to be used.

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

Access token or its configuration.

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

            
setAuthUrl() public method

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

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

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

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

            
setReturnUrl() public method

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

Return URL

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

            
setState() protected method

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

Sets persistent state.

protected setState( string $key, mixed $value ): $this
$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;
}

            
setYiisoftFactory() public method

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

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