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

Protected Methods

Hide inherited methods

Method Description Defined By
createToken() Creates token from its configuration. Yiisoft\Yii\AuthClient\OAuth
defaultNormalizeUserAttributeMap() Returns the default {@see normalizeUserAttributeMap} value. Yiisoft\Yii\AuthClient\AuthClient
defaultReturnUrl() Composes default {@see returnUrl} value. Yiisoft\Yii\AuthClient\OAuth
defaultViewOptions() Returns the default {@see viewOptions} value. Yiisoft\Yii\AuthClient\AuthClient
getDefaultScope() Yiisoft\Yii\AuthClient\OAuth
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
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

$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 {@see \Yiisoft\Yii\AuthClient\UriInterface::getPath()}} value of {@see \Yiisoft\Yii\AuthClient\httpClient}. Note: changing this property will take no effect after {@see \Yiisoft\Yii\AuthClient\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 mixed __construct ( \Psr\Http\Client\ClientInterface $httpClient, \Psr\Http\Message\RequestFactoryInterface $requestFactory, Yiisoft\Yii\AuthClient\StateStorage\StateStorageInterface $stateStorage, \Yiisoft\Factory\Factory $factory )
$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 {@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: ' . (string)$response->getBody()
        );
    }
    return (array)Json::decode($response->getBody()->getContents());
}

            
applyAccessTokenToRequest() public abstract method

Applies access token to the HTTP request instance.

public abstract \Psr\Http\Message\RequestInterface applyAccessTokenToRequest ( \Psr\Http\Message\RequestInterface $request, Yiisoft\Yii\AuthClient\OAuthToken $accessToken )
$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 \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 abstract method
public abstract string buildAuthUrl ( \Psr\Http\Message\ServerRequestInterface $incomingRequest, array $params )
$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 {@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

Creates token from its configuration.

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

protected Yiisoft\Yii\AuthClient\OAuthToken createToken ( array $tokenConfig )
$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 {@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

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
{
    return (string)$request->getUri();
}

            
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,
    ];
}

            
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;
}

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

                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 string getClientId ( )

                public function getClientId(): string;

            
getDefaultScope() protected method

protected string getDefaultScope ( )

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

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

Service name.

                public function getName(): string;

            
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;
}

            
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;
}

            
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 abstract method
public abstract string getTitle ( )
return string

Service title.

                public function getTitle(): string;

            
getViewOptions() public method
public array getViewOptions ( )
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 \Yiisoft\Factory\Factory getYiisoftFactory ( )

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

            
refreshAccessToken() public abstract method

Gets new auth token to replace expired one.

public abstract 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.

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

            
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

Restores access token.

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

                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 $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

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)) {
        /**
         * @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 void setAuthUrl ( string $authUrl )
$authUrl string

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

            
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;
}

            
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;
}

            
setYiisoftFactory() public method

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

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