Class yii\authclient\AuthAction
Inheritance | yii\authclient\AuthAction » yii\base\Action |
---|---|
Available since extension's version | 2.0 |
Source Code | https://github.com/yiisoft/yii2-authclient/blob/master/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
Property | Type | Description | Defined By |
---|---|---|---|
$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 |
Public Methods
Method | Description | Defined By |
---|---|---|
getCancelUrl() | yii\authclient\AuthAction | |
getSuccessUrl() | yii\authclient\AuthAction | |
redirect() | Redirect to the given URL or simply close the popup window. | yii\authclient\AuthAction |
redirectCancel() | Redirect to the $cancelUrl or simply close the popup window. | yii\authclient\AuthAction |
redirectSuccess() | Redirect to the URL. If URL is null, $successUrl will be used. | yii\authclient\AuthAction |
run() | Runs the action. | yii\authclient\AuthAction |
setCancelUrl() | yii\authclient\AuthAction | |
setSuccessUrl() | yii\authclient\AuthAction |
Protected Methods
Method | Description | Defined By |
---|---|---|
auth() | 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
Name of the auth client collection application component. It should point to yii\authclient\Collection instance.
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.
Name or alias of the view file, which should be rendered in order to perform redirection. If not set default one will be used.
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($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.
Method Details
protected \yii\web\Response auth ( $client ) | ||
$client | mixed |
Auth client instance. |
return | \yii\web\Response |
Response instance. |
---|---|---|
throws | \yii\base\NotSupportedException |
on invalid client. |
protected function auth($client)
{
if ($client instanceof OpenId) {
return $this->authOpenId($client);
} elseif ($client instanceof OAuth2) {
return $this->authOAuth2($client);
} elseif ($client instanceof OAuth1) {
return $this->authOAuth1($client);
} else {
throw new NotSupportedException('Provider "' . get_class($client) . '" is not supported.');
}
}
Performs OAuth1 auth flow.
protected \yii\web\Response authOAuth1 ( $client ) | ||
$client | yii\authclient\OAuth1 |
Auth client instance. |
return | \yii\web\Response |
Action response. |
---|
protected function authOAuth1($client)
{
// user denied error
if (isset($_GET['denied'])) {
return $this->redirectCancel();
}
if (isset($_REQUEST['oauth_token'])) {
$oauthToken = $_REQUEST['oauth_token'];
}
if (!isset($oauthToken)) {
// Get request token.
$requestToken = $client->fetchRequestToken();
// Get authorization URL.
$url = $client->buildAuthUrl($requestToken);
// Redirect to authorization URL.
return Yii::$app->getResponse()->redirect($url);
} else {
// Upgrade to access token.
$client->fetchAccessToken();
return $this->authSuccess($client);
}
}
Performs OAuth2 auth flow.
protected \yii\web\Response authOAuth2 ( $client ) | ||
$client | yii\authclient\OAuth2 |
Auth client instance. |
return | \yii\web\Response |
Action response. |
---|---|---|
throws | \yii\base\Exception |
on failure. |
protected function authOAuth2($client)
{
if (isset($_GET['error'])) {
if ($_GET['error'] == 'access_denied') {
// user denied error
return $this->redirectCancel();
} else {
// request error
if (isset($_GET['error_description'])) {
$errorMessage = $_GET['error_description'];
} elseif (isset($_GET['error_message'])) {
$errorMessage = $_GET['error_message'];
} else {
$errorMessage = http_build_query($_GET);
}
throw new Exception('Auth error: ' . $errorMessage);
}
}
// Get the access_token and save them to the session.
if (isset($_GET['code'])) {
$code = $_GET['code'];
$token = $client->fetchAccessToken($code);
if (!empty($token)) {
return $this->authSuccess($client);
} else {
return $this->redirectCancel();
}
} else {
$url = $client->buildAuthUrl();
return Yii::$app->getResponse()->redirect($url);
}
}
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)
{
if (!empty($_REQUEST['openid_mode'])) {
switch ($_REQUEST['openid_mode']) {
case 'id_res':
if ($client->validate()) {
return $this->authSuccess($client);
} else {
throw new HttpException(400, 'Unable to complete the authentication because the required data was not received.');
}
break;
case 'cancel':
$this->redirectCancel();
break;
default:
throw new HttpException(400);
break;
}
} else {
$url = $client->buildAuthUrl();
return Yii::$app->getResponse()->redirect($url);
}
return $this->redirectCancel();
}
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();
}
Creates default $cancelUrl value.
protected string defaultCancelUrl ( ) | ||
return | string |
Cancel URL value. |
---|
protected function defaultCancelUrl()
{
return Url::to(Yii::$app->getUser()->loginUrl);
}
Creates default $successUrl value.
protected string defaultSuccessUrl ( ) | ||
return | string |
Success URL value. |
---|
protected function defaultSuccessUrl()
{
return Yii::$app->getUser()->getReturnUrl();
}
public string getCancelUrl ( ) | ||
return | string |
Cancel URL. |
---|
public function getCancelUrl()
{
if (empty($this->_cancelUrl)) {
$this->_cancelUrl = $this->defaultCancelUrl();
}
return $this->_cancelUrl;
}
public string getSuccessUrl ( ) | ||
return | string |
Successful URL. |
---|
public function getSuccessUrl()
{
if (empty($this->_successUrl)) {
$this->_successUrl = $this->defaultSuccessUrl();
}
return $this->_successUrl;
}
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;
}
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);
}
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);
}
Runs the action.
public void run ( ) |
public function run()
{
if (!empty($_GET[$this->clientIdGetParamName])) {
$clientId = $_GET[$this->clientIdGetParamName];
/* @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);
} else {
throw new NotFoundHttpException();
}
}
public void setCancelUrl ( $url ) | ||
$url | string |
Cancel URL. |
public function setCancelUrl($url)
{
$this->_cancelUrl = $url;
}
public void setSuccessUrl ( $url ) | ||
$url | string |
Successful URL. |
public function setSuccessUrl($url)
{
$this->_successUrl = $url;
}