晓鹿牛羊/yii2-oauth2-server

PHP OAuth2 Server

安装: 5

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 0

开放问题: 0

类型:yii2-extension

dev-master / 1.0.x-dev 2016-11-08 07:46 UTC

This package is not auto-updated.

Last update: 2024-09-23 15:13:13 UTC


README

用于实现 OAuth2 服务器(https://github.com/bshaffer/oauth2-server-php)的包装器

安装

安装此扩展的首选方式是通过 composer

运行以下命令之一:

php composer.phar require --prefer-dist sxlxnyw/yii2-oauth2-server "*"

"sxlxnyw/yii2-oauth2-server": "*"

将以下内容添加到 composer.json 文件的 require 部分。

要使用此扩展,只需将以下代码添加到您的应用程序配置中

'oauth2' => [
    'class' => 'sxlxnyw\yii2\oauth2server\Module',
    'options' => [
        'token_param_name' => 'accessToken',
        'access_lifetime' => 3600 * 24
    ],
    'storageMap' => [
        'user_credentials' => 'common\models\User'
    ],
    'grantTypes' => [
        'client_credentials' => [
            'class' => 'OAuth2\GrantType\ClientCredentials',
            'allow_public_clients' => false
        ],
        'user_credentials' => [
            'class' => 'OAuth2\GrantType\UserCredentials'
        ],
        'refresh_token' => [
            'class' => 'OAuth2\GrantType\RefreshToken',
            'always_issue_new_refresh_token' => true
        ]
    ],
]

common\models\User - 实现接口 \OAuth2\Storage\UserCredentialsInterface 的用户模型,因此 OAuth2 凭证数据存储在用户表中

下一步,您应该运行迁移

yii migrate --migrationPath=@vendor/sxlxnyw/yii2-oauth2-server/migrations

此迁移创建 OAuth2 数据库架构并插入测试用户凭据 testclient:testpass 用于 http://fake/

向 urlManager 添加 URL 规则

'urlManager' => [
    'rules' => [
        'POST oauth2/<action:\w+>' => 'oauth2/default/<action>',
        ...
    ]
]

用法

要使用此扩展,只需为您的基控制器添加行为

use yii\helpers\ArrayHelper;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use sxlxnyw\yii2\oauth2server\filters\ErrorToExceptionFilter;
use sxlxnyw\yii2\oauth2server\filters\auth\CompositeAuth;

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

更多信息请见 https://github.com/bshaffer/oauth2-server-php