Class yii\authclient\AuthAction

Inheritanceyii\authclient\AuthAction » yii\base\Action
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-authclient/blob/master/src/AuthAction.php

AuthAction performs authentication via different auth clients.

It supports yii\authclient\OpenId, yii\authclient\OAuth1 and yii\authclient\OAuth2 client types.

Usage:

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'auth' => [
                'class' => 'yii\authclient\AuthAction',
                'successCallback' => [$this, 'successCallback'],
            ],
        ]
    }

    public function successCallback($client)
    {
        $attributes = $client->getUserAttributes();
        // user login or signup comes here
    }
}

Usually authentication via external services is performed inside the popup window. This action handles the redirection and closing of popup window correctly.

See also:

Public Properties

Hide inherited properties

Property Type Description Defined By
$cancelCallback callable PHP callback, which should be triggered in case of authentication cancelation. yii\authclient\AuthAction
$cancelUrl string Cancel URL. yii\authclient\AuthAction
$clientCollection string Name of the auth client collection application component. yii\authclient\AuthAction
$clientIdGetParamName string Name of the GET param, which is used to passed auth client id to this action. yii\authclient\AuthAction
$redirectView string Name or alias of the view file, which should be rendered in order to perform redirection. yii\authclient\AuthAction
$successCallback callable PHP callback, which should be triggered in case of successful authentication. yii\authclient\AuthAction
$successUrl string Successful URL. yii\authclient\AuthAction
$user \yii\web\User|array|string The User object or the application component ID of the user component. yii\authclient\AuthAction

Protected Methods

Hide inherited methods

Method Description Defined By
auth() Perform authentication for the given client. yii\authclient\AuthAction
authCancel() This method is invoked in case of authentication cancelation. yii\authclient\AuthAction
authOAuth1() Performs OAuth1 auth flow. yii\authclient\AuthAction
authOAuth2() Performs OAuth2 auth flow. yii\authclient\AuthAction
authOpenId() Performs OpenID auth flow. yii\authclient\AuthAction
authSuccess() This method is invoked in case of successful authentication via auth client. yii\authclient\AuthAction
defaultCancelUrl() Creates default $cancelUrl value. yii\authclient\AuthAction
defaultSuccessUrl() Creates default $successUrl value. yii\authclient\AuthAction

Property Details

Hide inherited properties

$cancelCallback public property (available since version 2.1.5)

PHP callback, which should be triggered in case of authentication cancelation. This callback should accept yii\authclient\ClientInterface instance as an argument. For example:

public function onAuthCancel(ClientInterface $client)
{
    // set flash, logging, etc.
}

If this callback returns Response instance, it will be used as action response, otherwise redirection to $cancelUrl will be performed.

public callable $cancelCallback null
$cancelUrl public property

Cancel URL.

public string $cancelUrl null
$clientCollection public property

Name of the auth client collection application component. It should point to yii\authclient\Collection instance.

public string $clientCollection 'authClientCollection'
$clientIdGetParamName public property

Name of the GET param, which is used to passed auth client id to this action. Note: watch for the naming, make sure you do not choose name used in some auth protocol.

public string $clientIdGetParamName 'authclient'
$redirectView public property

Name or alias of the view file, which should be rendered in order to perform redirection. If not set - default one will be used.

public string $redirectView null
$successCallback public property

PHP callback, which should be triggered in case of successful authentication. This callback should accept yii\authclient\ClientInterface instance as an argument. For example:

public function onAuthSuccess(ClientInterface $client)
{
    $attributes = $client->getUserAttributes();
    // user login or signup comes here
}

If this callback returns Response instance, it will be used as action response, otherwise redirection to $successUrl will be performed.

public callable $successCallback null
$successUrl public property

Successful URL.

public string $successUrl null
$user public property (available since version 2.1.8)

The User object or the application component ID of the user component.

public \yii\web\User|array|string $user 'user'

Method Details

Hide inherited methods

auth() protected method

Perform authentication for the given client.

protected \yii\web\Response auth ( $client, $authUrlParams = [] )
$client mixed

Auth client instance.

$authUrlParams array

Additional auth GET params.

return \yii\web\Response

Response instance.

throws \yii\base\NotSupportedException

on invalid client.

                protected function auth($client, $authUrlParams = [])
{
    if ($client instanceof OAuth2) {
        return $this->authOAuth2($client, $authUrlParams);
    } elseif ($client instanceof OAuth1) {
        return $this->authOAuth1($client, $authUrlParams);
    } elseif ($client instanceof OpenId) {
        return $this->authOpenId($client);
    }
    throw new NotSupportedException('Provider "' . get_class($client) . '" is not supported.');
}

            
authCancel() protected method (available since version 2.1.5)

This method is invoked in case of authentication cancelation.

protected \yii\web\Response authCancel ( $client )
$client yii\authclient\ClientInterface

Auth client instance.

return \yii\web\Response

Response instance.

                protected function authCancel($client)
{
    if ($this->cancelCallback !== null) {
        $response = call_user_func($this->cancelCallback, $client);
        if ($response instanceof Response) {
            return $response;
        }
    }
    return $this->redirectCancel();
}

            
authOAuth1() protected method

Performs OAuth1 auth flow.

protected \yii\web\Response authOAuth1 ( $client, $authUrlParams = [] )
$client yii\authclient\OAuth1

Auth client instance.

$authUrlParams array

Additional auth GET params.

return \yii\web\Response

Action response.

                protected function authOAuth1($client, $authUrlParams = [])
{
    $request = Yii::$app->getRequest();
    // user denied error
    if ($request->get('denied') !== null) {
        return $this->authCancel($client);
    }
    if (($oauthToken = $request->get('oauth_token', $request->post('oauth_token'))) !== null) {
        // Upgrade to access token.
        $client->fetchAccessToken($oauthToken);
        return $this->authSuccess($client);
    }
    // Get request token.
    $requestToken = $client->fetchRequestToken();
    // Get authorization URL.
    $url = $client->buildAuthUrl($requestToken, $authUrlParams);
    // Redirect to authorization URL.
    return Yii::$app->getResponse()->redirect($url);
}

            
authOAuth2() protected method

Performs OAuth2 auth flow.

protected \yii\web\Response authOAuth2 ( $client, $authUrlParams = [] )
$client yii\authclient\OAuth2

Auth client instance.

$authUrlParams array

Additional auth GET params.

return \yii\web\Response

Action response.

throws \yii\base\Exception

on failure.

                protected function authOAuth2($client, $authUrlParams = [])
{
    $request = Yii::$app->getRequest();
    if (($error = $request->get('error')) !== null) {
        if (
            $error === 'access_denied' ||
            $error === 'user_cancelled_login' ||
            $error === 'user_cancelled_authorize'
        ) {
            // user denied error
            return $this->authCancel($client);
        }
        // request error
        $errorMessage = $request->get('error_description', $request->get('error_message'));
        if ($errorMessage === null) {
            $errorMessage = http_build_query($request->get());
        }
        throw new Exception('Auth error: ' . $errorMessage);
    }
    // Get the access_token and save them to the session.
    if (($code = $request->get('code')) !== null) {
        $token = $client->fetchAccessToken($code);
        if (!empty($token)) {
            return $this->authSuccess($client);
        }
        return $this->authCancel($client);
    }
    $url = $client->buildAuthUrl($authUrlParams);
    return Yii::$app->getResponse()->redirect($url);
}

            
authOpenId() protected method

Performs OpenID auth flow.

protected \yii\web\Response authOpenId ( $client )
$client yii\authclient\OpenId

Auth client instance.

return \yii\web\Response

Action response.

throws \yii\base\Exception

on failure.

throws \yii\web\HttpException

on failure.

                protected function authOpenId($client)
{
    $request = Yii::$app->getRequest();
    $mode = $request->get('openid_mode', $request->post('openid_mode'));
    if (empty($mode)) {
        $url = $client->buildAuthUrl();
        return Yii::$app->getResponse()->redirect($url);
    }
    switch ($mode) {
        case 'id_res':
            if ($client->validate()) {
                return $this->authSuccess($client);
            }
            throw new HttpException(400, 'Unable to complete the authentication because the required data was not received.');
        case 'cancel':
            return $this->authCancel($client);
        default:
            throw new HttpException(400);
    }
}

            
authSuccess() protected method

This method is invoked in case of successful authentication via auth client.

protected \yii\web\Response authSuccess ( $client )
$client yii\authclient\ClientInterface

Auth client instance.

return \yii\web\Response

Response instance.

throws \yii\base\InvalidConfigException

on invalid success callback.

                protected function authSuccess($client)
{
    if (!is_callable($this->successCallback)) {
        throw new InvalidConfigException('"' . get_class($this) . '::$successCallback" should be a valid callback.');
    }
    $response = call_user_func($this->successCallback, $client);
    if ($response instanceof Response) {
        return $response;
    }
    return $this->redirectSuccess();
}

            
defaultCancelUrl() protected method

Creates default $cancelUrl value.

protected string defaultCancelUrl ( )
return string

Cancel URL value.

                protected function defaultCancelUrl()
{
    return Url::to($this->user->loginUrl);
}

            
defaultSuccessUrl() protected method

Creates default $successUrl value.

protected string defaultSuccessUrl ( )
return string

Success URL value.

                protected function defaultSuccessUrl()
{
    return $this->user->getReturnUrl();
}

            
getCancelUrl() public method

public string getCancelUrl ( )
return string

Cancel URL.

                public function getCancelUrl()
{
    if (empty($this->_cancelUrl)) {
        $this->_cancelUrl = $this->defaultCancelUrl();
    }
    return $this->_cancelUrl;
}

            
getSuccessUrl() public method

public string getSuccessUrl ( )
return string

Successful URL.

                public function getSuccessUrl()
{
    if (empty($this->_successUrl)) {
        $this->_successUrl = $this->defaultSuccessUrl();
    }
    return $this->_successUrl;
}

            
init() public method

public void init ( )

                public function init()
{
    parent::init();
    $this->user = Instance::ensure($this->user, User::className());
}

            
redirect() public method

Redirect to the given URL or simply close the popup window.

public \yii\web\Response redirect ( $url, $enforceRedirect true )
$url mixed

URL to redirect, could be a string or array config to generate a valid URL.

$enforceRedirect boolean

Indicates if redirect should be performed even in case of popup window.

return \yii\web\Response

Response instance.

                public function redirect($url, $enforceRedirect = true)
{
    $viewFile = $this->redirectView;
    if ($viewFile === null) {
        $viewFile = __DIR__ . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . 'redirect.php';
    } else {
        $viewFile = Yii::getAlias($viewFile);
    }
    $viewData = [
        'url' => $url,
        'enforceRedirect' => $enforceRedirect,
    ];
    $response = Yii::$app->getResponse();
    $response->content = Yii::$app->getView()->renderFile($viewFile, $viewData);
    return $response;
}

            
redirectCancel() public method

Redirect to the $cancelUrl or simply close the popup window.

public \yii\web\Response redirectCancel ( $url null )
$url string

URL to redirect.

return \yii\web\Response

Response instance.

                public function redirectCancel($url = null)
{
    if ($url === null) {
        $url = $this->getCancelUrl();
    }
    return $this->redirect($url, false);
}

            
redirectSuccess() public method

Redirect to the URL. If URL is null, $successUrl will be used.

public \yii\web\Response redirectSuccess ( $url null )
$url string

URL to redirect.

return \yii\web\Response

Response instance.

                public function redirectSuccess($url = null)
{
    if ($url === null) {
        $url = $this->getSuccessUrl();
    }
    return $this->redirect($url);
}

            
run() public method

Runs the action.

public void run ( )

                public function run()
{
    $clientId = Yii::$app->getRequest()->getQueryParam($this->clientIdGetParamName);
    if (!empty($clientId)) {
        /* @var $collection \yii\authclient\Collection */
        $collection = Yii::$app->get($this->clientCollection);
        if (!$collection->hasClient($clientId)) {
            throw new NotFoundHttpException("Unknown auth client '{$clientId}'");
        }
        $client = $collection->getClient($clientId);
        return $this->auth($client);
    }
    throw new NotFoundHttpException();
}

            
setCancelUrl() public method

public void setCancelUrl ( $url )
$url string

Cancel URL.

                public function setCancelUrl($url)
{
    $this->_cancelUrl = $url;
}

            
setSuccessUrl() public method

public void setSuccessUrl ( $url )
$url string

Successful URL.

                public function setSuccessUrl($url)
{
    $this->_successUrl = $url;
}