Final Class Yiisoft\Yii\AuthClient\Client\VKontakte
VKontakte allows authentication via VKontakte OAuth 2.0
In order to use VKontakte OAuth you must register your application at https://dev.vk.ru.
See also:
- https://id.vk.ru/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/auth-without-sdk/auth-without-sdk-web
- https://id.vk.ru/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/how-auth-works/auth-flow-web
- https://id.vk.ru/about/business/go/accounts/{USER}/apps/{APPLICATION_ID}/edit Authorization Code Workflow Client Id => VKontakte Application Id Authorization Code Workflow Secret Id => Access Keys: Protected Key ... to perform requests to the VKontakte API on behalf of the application (used here) Access Keys: Service Key ... to perform requests to the VKontakte API on behalf of the application (not used here) when user authorization is not required.
Protected 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 | Yiisoft\Yii\AuthClient\Client\VKontakte | |
| $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\VKontakte | |
| $factory | \Yiisoft\Factory\Factory | Yiisoft\Yii\AuthClient\OAuth2 | |
| $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 | Yiisoft\Yii\AuthClient\OAuth2 | |
| $scope | string | String auth request scope. | Yiisoft\Yii\AuthClient\OAuth |
| $session | \Yiisoft\Session\SessionInterface | Yiisoft\Yii\AuthClient\OAuth2 | |
| $tokenUrl | string | Yiisoft\Yii\AuthClient\Client\VKontakte | |
| $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
Protected Methods
Property Details
Method Details
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);
}
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: ' . (string)$response->getBody()
);
}
return (array)Json::decode($response->getBody()->getContents());
}
| 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 | |
#[\Override]
public function applyAccessTokenToRequest(RequestInterface $request, OAuthToken $accessToken): RequestInterface
{
return RequestUtil::addParams(
$request,
[
'access_token' => $accessToken->getToken(),
]
);
}
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.
| 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
{
return RequestUtil::addParams(
$request,
[
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
]
);
}
| 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);
}
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. |
|---|---|---|
#[\Override]
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, $params));
}
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);
}
| 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);
}
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. |
|---|---|---|
#[\Override]
protected function createToken(array $tokenConfig = []): OAuthToken
{
$tokenConfig['tokenParamKey'] = 'access_token';
return parent::createToken($tokenConfig);
}
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 [];
}
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. |
|---|---|---|
#[\Override]
protected function defaultReturnUrl(ServerRequestInterface $request): string
{
$params = $request->getQueryParams();
unset($params['code'], $params['state']);
return (string)$request->getUri()->withQuery(http_build_query($params, '', '&', PHP_QUERY_RFC3986));
}
| protected integer[] defaultViewOptions ( ) |
#[\Override]
protected function defaultViewOptions(): array
{
return [
'popupWidth' => 860,
'popupHeight' => 480,
];
}
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) {
/**
* @psalm-suppress MixedAssignment
*/
$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');
}
$defaultParams = [
'code' => $authCode,
'redirect_uri' => $this->getOauth2ReturnUrl(),
];
$request = $this->createRequest('POST', $this->tokenUrl);
$request = RequestUtil::addParams($request, array_merge($defaultParams, $params));
$request = $this->applyClientCredentialsToRequest($request);
$response = $this->sendRequest($request);
$contents = $response->getBody()->getContents();
$output = $this->parse_str_clean($contents);
$token = new OAuthToken();
/**
* @var string $key
* @var string $value
*/
foreach ($output as $key => $value) {
$token->setParam($key, $value);
}
return $token;
}
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) {
/**
* @psalm-suppress MixedAssignment
*/
$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('Content-Type', 'application/x-www-form-urlencoded');
$request->getBody()->write(http_build_query($requestBody));
try {
$response = $this->httpClient->sendRequest($request);
$body = $response->getBody()->getContents();
if (strlen($body) > 0) {
$output = (array) json_decode($body, true);
} else {
$output = [];
}
} catch (\Throwable $e) {
$output = [];
}
$token = new OAuthToken();
/**
* @var string $key
* @var string $value
*/
foreach ($output as $key => $value) {
$token->setParam($key, $value);
}
return $token;
}
Defined in: Yiisoft\Yii\AuthClient\OAuth2::generateAuthState()
Generates the auth state value.
| protected string generateAuthState ( ) | ||
| return | string |
Auth state value. |
|---|---|---|
protected function generateAuthState(): string
{
$baseString = static::class . '-' . time();
$sessionId = $this->session->getId();
if (null !== $sessionId) {
if ($this->session->isActive()) {
$baseString .= '-' . $sessionId;
}
}
return hash('sha256', uniqid($baseString, true));
}
Defined in: Yiisoft\Yii\AuthClient\OAuth::getAccessToken()
| 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;
}
| public string getButtonClass ( ) |
#[\Override]
public function getButtonClass(): string
{
return 'btn btn-dark';
}
Defined in: Yiisoft\Yii\AuthClient\OAuth2::getClientId()
| public string getClientId ( ) |
#[\Override]
public function getClientId(): string
{
return $this->clientId;
}
Defined in: Yiisoft\Yii\AuthClient\OAuth2::getClientSecret()
| public string getClientSecret ( ) |
public function getClientSecret(): string
{
return $this->clientSecret;
}
| protected string getDefaultScope ( ) |
#[\Override]
protected function getDefaultScope(): string
{
return 'email phone';
}
| public array getNormalizeUserAttributeMap ( ) | ||
| return | array |
Normalize user attribute map. |
|---|---|---|
public function getNormalizeUserAttributeMap(): array
{
if (empty($this->normalizeUserAttributeMap)) {
$this->normalizeUserAttributeMap = $this->defaultNormalizeUserAttributeMap();
}
return $this->normalizeUserAttributeMap;
}
| public string getOauth2ReturnUrl ( ) |
public function getOauth2ReturnUrl(): string
{
return $this->returnUrl;
}
| public \Psr\Http\Message\RequestFactoryInterface getRequestFactory ( ) |
public function getRequestFactory(): RequestFactoryInterface
{
return $this->requestFactory;
}
Defined in: Yiisoft\Yii\AuthClient\OAuth::getReturnUrl()
| 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;
}
Defined in: Yiisoft\Yii\AuthClient\OAuth::getScope()
| public string getScope ( ) |
public function getScope(): string
{
if ($this->scope === null) {
return $this->getDefaultScope();
}
return $this->scope;
}
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');
}
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);
}
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() . '_';
}
Defined in: Yiisoft\Yii\AuthClient\OAuth2::getTokenUrl()
| public string getTokenUrl ( ) |
public function getTokenUrl(): string
{
return $this->tokenUrl;
}
| 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;
}
| public \Yiisoft\Factory\Factory getYiisoftFactory ( ) |
public function getYiisoftFactory(): YiisoftFactory
{
return $this->factory;
}
Defined in: Yiisoft\Yii\AuthClient\OAuth2::refreshAccessToken()
Gets new auth token to replace expired one.
| 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. |
|---|---|---|
#[\Override]
public function refreshAccessToken(OAuthToken $token): OAuthToken
{
$params = [
'grant_type' => 'refresh_token',
];
$params = array_merge($token->getParams(), $params);
$request = $this->createRequest('POST', $this->tokenUrl);
$request = RequestUtil::addParams($request, $params);
$request = $this->applyClientCredentialsToRequest($request);
$response = $this->sendRequest($request);
$contents = $response->getBody()->getContents();
$output = $this->parse_str_clean($contents);
$token = new OAuthToken();
/**
* @var string $key
* @var string $value
*/
foreach ($output as $key => $value) {
$token->setParam($key, $value);
}
return $token;
}
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);
}
Defined in: Yiisoft\Yii\AuthClient\OAuth::restoreAccessToken()
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;
}
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);
}
Defined in: Yiisoft\Yii\AuthClient\AuthClient::sendRequest()
| 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);
}
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)) {
/**
* @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);
}
}
Defined in: Yiisoft\Yii\AuthClient\OAuth::setAuthUrl()
| public void setAuthUrl ( string $authUrl ) | ||
| $authUrl | string | |
public function setAuthUrl(string $authUrl): void
{
$this->authUrl = $authUrl;
}
Defined in: Yiisoft\Yii\AuthClient\OAuth2::setClientId()
| public void setClientId ( string $clientId ) | ||
| $clientId | string | |
public function setClientId(string $clientId): void
{
$this->clientId = $clientId;
}
Defined in: Yiisoft\Yii\AuthClient\OAuth2::setClientSecret()
| public void setClientSecret ( string $clientSecret ) | ||
| $clientSecret | string | |
public function setClientSecret(string $clientSecret): void
{
$this->clientSecret = $clientSecret;
}
| public void setOauth2ReturnUrl ( string $returnUrl ) | ||
| $returnUrl | string | |
public function setOauth2ReturnUrl(string $returnUrl): void
{
$this->returnUrl = $returnUrl;
}
| public void setRequestFactory ( \Psr\Http\Message\RequestFactoryInterface $requestFactory ) | ||
| $requestFactory | \Psr\Http\Message\RequestFactoryInterface | |
public function setRequestFactory(RequestFactoryInterface $requestFactory): void
{
$this->requestFactory = $requestFactory;
}
Defined in: Yiisoft\Yii\AuthClient\OAuth::setReturnUrl()
| public void setReturnUrl ( string $returnUrl ) | ||
| $returnUrl | string |
Return URL |
public function setReturnUrl(string $returnUrl): void
{
$this->returnUrl = $returnUrl;
}
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;
}
Defined in: Yiisoft\Yii\AuthClient\OAuth2::setTokenUrl()
| public void setTokenUrl ( string $tokenUrl ) | ||
| $tokenUrl | string | |
public function setTokenUrl(string $tokenUrl): void
{
$this->tokenUrl = $tokenUrl;
}
| public void setYiisoftFactory ( \Yiisoft\Factory\Factory $factory ) | ||
| $factory | \Yiisoft\Factory\Factory | |
public function setYiisoftFactory(YiisoftFactory $factory): void
{
$this->factory = $factory;
}
Example answer: [ 'access_token' => 'XXXXX', 'refresh_token' => 'XXXXX', 'expires_in' => 0, 'user_id' => 1234567890, 'state' => 'XXX', 'scope' => 'email phone' ]
See also https://id.vk.ru/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/auth-without-sdk/auth-without-sdk-web Step 6: Getting New Access Token After Previous Token Expires.
| public mixed step6GettingNewAccessTokenAfterPreviousExpires ( string $refreshToken, string $clientId, string $deviceId, string $state, \Psr\Http\Client\ClientInterface $httpClient, \Psr\Http\Message\RequestFactoryInterface $requestFactory ) | ||
| $refreshToken | string | |
| $clientId | string | |
| $deviceId | string | |
| $state | string | |
| $httpClient | \Psr\Http\Client\ClientInterface | |
| $requestFactory | \Psr\Http\Message\RequestFactoryInterface | |
public function step6GettingNewAccessTokenAfterPreviousExpires(
string $refreshToken,
string $clientId,
string $deviceId,
string $state,
ClientInterface $httpClient,
RequestFactoryInterface $requestFactory
): mixed {
$url = $this->tokenUrl;
$data = [
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
'client_id' => $clientId,
'device_id' => $deviceId,
'state' => $state,
];
$request = $requestFactory->createRequest('POST', $url)
->withHeader('Content-Type', 'application/x-www-form-urlencoded');
// Add form body
$request->getBody()->write(http_build_query($data));
try {
$response = $httpClient->sendRequest($request);
$body = $response->getBody()->getContents();
if ($response->getStatusCode() >= 400) {
return [
'error' => 'Error:' . $response->getReasonPhrase(),
];
}
if (strlen($body) > 0) {
return json_decode($body, true);
}
} catch (\Throwable $e) {
return [
'error' => 'Exception: ' . $e->getMessage(),
];
}
return [];
}
Example answer: ["response" => 1]
See also https://id.vk.ru/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/auth-without-sdk/auth-without-sdk-web #Step 7. Token invalidation (logout) Converted to use PSR-18 ClientInterface and PSR-17 RequestFactoryInterface instead of curl.
| public array step7TokenInvalidationWithClientId ( Yiisoft\Yii\AuthClient\OAuthToken $token, string $clientId, \Psr\Http\Client\ClientInterface $httpClient, \Psr\Http\Message\RequestFactoryInterface $requestFactory ) | ||
| $token | Yiisoft\Yii\AuthClient\OAuthToken | |
| $clientId | string | |
| $httpClient | \Psr\Http\Client\ClientInterface | |
| $requestFactory | \Psr\Http\Message\RequestFactoryInterface | |
public function step7TokenInvalidationWithClientId(
OAuthToken $token,
string $clientId,
ClientInterface $httpClient,
RequestFactoryInterface $requestFactory
): array {
$url = 'https://id.vk.ru/oauth2/user_info';
$tokenString = (string)$token->getParam('access_token');
if (strlen($tokenString) === 0) {
return [];
}
$fullUrl = $url . '?client_id=' . urlencode($clientId) . '&access_token=' . urlencode($tokenString);
$request = $requestFactory->createRequest('GET', $fullUrl);
try {
/** @var ResponseInterface $response */
$response = $httpClient->sendRequest($request);
$body = $response->getBody()->getContents();
if (!empty($body)) {
return (array) json_decode($body, true);
}
} catch (\Throwable) {
// Optionally log error: $e->getMessage()
return [];
}
return [];
}
Example Answer: [ "user" => [ "user_id" => "1234567890", "first_name" => "Ivan", "last_name" => "Ivanov", "phone" => "79991234567", "avatar" => "https://pp.userapi.com/60tZWMo4SmwcploUVl9XEt8ufnTTvDUmQ6Bj1g/mmv1pcj63C4.png", "email" => "ivan_i123@vk.ru", "sex" => 2, "verified" => false, "birthday" => "01.01.2000" ] ]
See also https://id.vk.ru/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/auth-without-sdk/auth-without-sdk-web #Step 8. (Optional) Obtaining user data.
| public array step8ObtainingUserDataArrayWithClientId ( Yiisoft\Yii\AuthClient\OAuthToken $token, string $clientId, \Psr\Http\Client\ClientInterface $httpClient, \Psr\Http\Message\RequestFactoryInterface $requestFactory ) | ||
| $token | Yiisoft\Yii\AuthClient\OAuthToken | |
| $clientId | string | |
| $httpClient | \Psr\Http\Client\ClientInterface | |
| $requestFactory | \Psr\Http\Message\RequestFactoryInterface | |
public function step8ObtainingUserDataArrayWithClientId(
OAuthToken $token,
string $clientId,
ClientInterface $httpClient,
RequestFactoryInterface $requestFactory
): array {
$url = 'https://id.vk.ru/oauth2/user_info';
$tokenString = (string)$token->getParam('access_token');
if (strlen($tokenString) === 0) {
return [];
}
$fullUrl = $url . '?client_id=' . urlencode($clientId) . '&access_token=' . urlencode($tokenString);
$request = $requestFactory->createRequest('GET', $fullUrl);
try {
/** @var ResponseInterface $response */
$response = $httpClient->sendRequest($request);
$body = $response->getBody()->getContents();
if (strlen($body) > 0) {
return (array)json_decode($body, true);
}
} catch (\Throwable) {
// Optionally log error: $e->getMessage()
return [];
}
return [];
}
Example answer: [ "user" => [ "user_id" => "1234567890", "first_name" => "Ivan", "last_name" => "Ivanov", "avatar" => "https://pp.userapi.com/60tZWMo4SmwcploUVl9XEt8ufnTTvDUmQ6Bj1g/mmv1pcj63C4.png", "sex" => 2, "verified" => false ] ]
See also https://id.vk.ru/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/auth-without-sdk/auth-without-sdk-web #Step 9. (Optional) Getting public user data.
| public array step9GetPublicUserDataArrayWithClientId ( string $clientId, string $userId, \Psr\Http\Client\ClientInterface $httpClient, \Psr\Http\Message\RequestFactoryInterface $requestFactory ) | ||
| $clientId | string | |
| $userId | string | |
| $httpClient | \Psr\Http\Client\ClientInterface | |
| $requestFactory | \Psr\Http\Message\RequestFactoryInterface | |
public function step9GetPublicUserDataArrayWithClientId(
string $clientId,
string $userId,
ClientInterface $httpClient,
RequestFactoryInterface $requestFactory
): array {
$fullUrl = $this->endpoint . '?client_id=' . urlencode($clientId) . '&user_id=' . urlencode($userId);
$request = $requestFactory->createRequest('GET', $fullUrl);
try {
/** @var ResponseInterface $response */
$response = $httpClient->sendRequest($request);
$body = $response->getBody()->getContents();
if (strlen($body) > 0) {
return (array) json_decode($body, true);
}
} catch (\Throwable) {
// Optionally log error: $e->getMessage()
return [];
}
return [];
}
| public self withValidateAuthState ( ) |
public function withValidateAuthState(): self
{
$new = clone $this;
$new->validateAuthState = true;
return $new;
}
| public self withoutValidateAuthState ( ) |
public function withoutValidateAuthState(): self
{
$new = clone $this;
$new->validateAuthState = false;
return $new;
}
Signup or Login in order to comment.