PHP code example of deadmantfa / yii2-oauth2-server

1. Go to this page and download the library: Download deadmantfa/yii2-oauth2-server 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/ */

    

deadmantfa / yii2-oauth2-server example snippets


return [
    // ...
    'bootstrap' => [
        'oauth2', // ensures module is bootstrapped
        // ...
    ],
    'modules' => [
        'oauth2' => [
            'class' => \deadmantfa\yii2\oauth2\server\Module::class,
            
            // Your key file paths:
            'privateKey' => __DIR__ . '/../oauth2/private.key',
            'publicKey'  => __DIR__ . '/../oauth2/public.key',

            // Encryption key used for JWT, typically 32+ bytes
            'encryptionKey' => 'some-random-binary-string',
            
            // Example: define any custom Repositories or model classes
            'components' => [
                'accessTokenRepository' => [
                    'class' => \deadmantfa\yii2\oauth2\server\components\Repositories\AccessTokenRepository::class,
                ],
                'refreshTokenRepository' => [
                    'class' => \deadmantfa\yii2\oauth2\server\components\Repositories\RefreshTokenRepository::class,
                ],
                'clientRepository' => [
                    'class' => \deadmantfa\yii2\oauth2\server\components\Repositories\ClientRepository::class,
                ],
                'scopeRepository' => [
                    'class' => \deadmantfa\yii2\oauth2\server\components\Repositories\ScopeRepository::class,
                ],
                // ...
            ],

            // Optional caching logic for repositories
            'cache' => [
                \League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface::class => [
                    'cacheDuration' => 3600,
                    'cacheDependency' => new \yii\caching\FileDependency(['fileName' => 'AccessTokenRepoCache.txt']),
                ],
                // ...
            ],

            // Register the grant types you want
            'enableGrantTypes' => static function (\deadmantfa\yii2\oauth2\server\Module $module) {
                $server = $module->authorizationServer;
                
                // Password + Refresh Token Grant
                $passwordGrant = new \League\OAuth2\Server\Grant\PasswordGrant(
                    $module->getComponent('userRepository'),
                    $module->getComponent('refreshTokenRepository')
                );
                $passwordGrant->setRefreshTokenTTL(new \DateInterval('P1M'));
                $server->enableGrantType($passwordGrant, new \DateInterval('PT1H'));

                // Client Credentials
                $server->enableGrantType(new \League\OAuth2\Server\Grant\ClientCredentialsGrant());
                
                // Refresh Token
                $refreshGrant = new \League\OAuth2\Server\Grant\RefreshTokenGrant(
                    $module->getComponent('refreshTokenRepository')
                );
                $refreshGrant->setRefreshTokenTTL(new \DateInterval('P1M'));
                $server->enableGrantType($refreshGrant, new \DateInterval('PT1H'));

                // (Optional) Revoke Grant
                $server->enableGrantType(new \deadmantfa\yii2\oauth2\server\components\Grant\RevokeGrant(
                    $module->getComponent('refreshTokenRepository'),
                    $module->publicKey
                ));
            },
        ],
    ],
    // ...
];


class MyUserRepository implements UserRepositoryInterface
{
    public function getUserEntityByUserCredentials($username, $password, $grantType, ClientEntityInterface $clientEntity)
    {
        $user = User::findOne(['username' => $username]);
        if (!$user || !Yii::$app->security->validatePassword($password, $user->password_hash)) {
            return null;
        }
        return $user; // which implements UserEntityInterface
    }
}

class MyApiController extends \yii\rest\ActiveController
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        unset($behaviors['authenticator']);
        unset($behaviors['rateLimiter']);

        /** @var \deadmantfa\yii2\oauth2\server\Module $auth */
        $auth = Yii::$app->getModule('oauth2');

        $behaviors['authenticator'] = [
            'class' => \yii\filters\auth\CompositeAuth::class,
            'authMethods' => [
                [
                    'class' => \deadmantfa\yii2\oauth2\server\components\AuthMethods\HttpBearerAuth::class,
                    'publicKey' => $auth->publicKey,
                    'cache'     => $auth->cache,
                ],
                // or add Mac tokens:
                // [
                //   'class' => \deadmantfa\yii2\oauth2\server\components\AuthMethods\HttpMacAuth::class,
                // ],
            ],
        ];

        $behaviors['rateLimiter'] = [
            'class' => \yii\filters\RateLimiter::class,
        ];

        return $behaviors;
    }
}


use \deadmantfa\yii2\oauth2\server\components\AuthMethods\HttpMacAuth;

$behaviors['authenticator'] = [
    'class' => \yii\filters\auth\CompositeAuth::class,
    'authMethods' => [
        [
            'class' => HttpMacAuth::class,
            'publicKey' => $auth->publicKey,
            'cache' => $auth->cache,
        ],
    ],
];

$server->enableGrantType(
    new \deadmantfa\yii2\oauth2\server\components\Grant\RevokeGrant(
        $module->refreshTokenRepository,
        $module->publicKey
    )
);

'on beforeRequest' => function ($event) {
    Yii::$app->attachBehavior('globalCors', [
        'class' => \yii\filters\Cors::class,
        'cors' => [
            'Origin' => ['https://yourfrontend.com'],
            'Access-Control-Allow-Credentials' => true,
            'Access-Control-Allow-Headers' => ['Authorization', 'Content-Type', 'X-Requested-With', 'Accept', 'Origin', 'Cache-Control', 'Pragma'],
            'Access-Control-Allow-Methods' => ['GET','POST','OPTIONS','PUT','DELETE'],
            'Access-Control-Max-Age' => 3600,
        ],
    ]);
},

'modules' => [
    'oauth2' => [
        'class' => \deadmantfa\yii2\oauth2\server\Module::class,
        'enableCors' => true,
        'corsConfig' => [
            'class' => \yii\filters\Cors::class,
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Allow-Methods' => ['POST','OPTIONS'],
                'Access-Control-Allow-Headers' => ['Authorization','Content-Type','X-Requested-With','Accept','Origin','Cache-Control','Pragma'],
                'Access-Control-Max-Age' => 3600,
            ],
        ],
        // ...
    ],
],
POST /oauth2/token
POST /oauth2/revoke
config/main.php
config/main.php