PHP code example of evgenidev / yii2-oauth2

1. Go to this page and download the library: Download evgenidev/yii2-oauth2 library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

evgenidev / yii2-oauth2 example snippets


'modules' => [
    'oauth2' => [
        'class' => \EvgeniDev\Yii2\OAuth2\Module::class,
        'accessTokenLifetime' => 3600 * 12,
        'identityClass' => \app\models\User::class,
    ],
],

'bootstrap' => [
    'oauth2',
],

'modules' => [
    'oauth2' => [
        'class' => \EvgeniDev\Yii2\OAuth2\Module::class::class,
        'accessTokenLifetime' => 3600 * 12,
        'identityClass' => \app\models\User::class,
        'authorizeViewPath' => '@app/views/your_view',
        'layout' => '@app/views/your_layout',
    ],
],

use yii\web\Response;

'modules' => [
    'oauth2' => [
        'class' => \EvgeniDev\Yii2\OAuth2\Module::class,
        'accessTokenLifetime' => 3600 * 12,
        'identityClass' => \app\models\User::class,
        'spaApp' => true,
        'responseFormat' => Response::FORMAT_XML,
    ],
],


use EvgeniDev\Yii2\OAuth2\Migrations\OAuth2;

/**
 * Your oauth migration.
 */
class m191117_223223_oauth extends OAuth2
{

}


'urlManager' => [
    'rules' => [
        'oauth2/authorize' => 'oauth2/authorize',
        'oauth2/access_token' => 'oauth2/access-token',
    ],
],

use yii\helpers\ArrayHelper;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;

class Controller extends \yii\rest\Controller
{
    /**
     * {@inheritDoc}
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'authenticator' => [
                'class' => CompositeAuth::class,
                'authMethods' => [
                    ['class' => HttpBearerAuth::class],
                    ['class' => QueryParamAuth::class, 'tokenParam' => 'accessToken'],
                ],
            ],
        ]);
    }
}

use EvgeniDev\Yii2\OAuth2\Records\OAuthAccessToken;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * User AR model.
 */
class User extends ActiveRecord implements IdentityInterface
{
    /**
     * {@inheritDoc}
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        $oauthToken = OAuthAccessToken::find()
            ->byAccessToken($token)
            ->one();
    
        if ($oauthToken === null || $oauthToken->getExpiresAt() < date('Y-m-d H:i:s')) {
            return null;
        }
    
        return self::find()
            ->where(['id' => $oauthToken->getUserID()])
            ->one();
    }
}
shell script
php composer.phar