roaresearch/yii2-oauth2-server

PHP 的 OAuth2 服务器

7.0.0 2022-10-28 20:46 UTC

This package is auto-updated.

Last update: 2024-09-24 03:33:49 UTC


README

实现 OAuth2 服务器的包装。

Latest Stable Version Total Downloads Code Coverage Scrutinizer Code Quality

Scrutinizer Build Status Scrutinizer

此项目是从 Filsh 原始项目 分支出来的,但更改不透明,请阅读 [UPGRADE.md] 以升级到最新版本。

安装

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

运行以下命令之一

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

"roaresearch/yii2-oauth2-server": "~6.0.0"

将其添加到 composer.json 的 require 部分。

用法

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

    'bootstrap' => ['oauth2'],
    'modules'=>[
        // other modules ...
        'oauth2' => [
            'class' => \roaresearch\yii2\oauth2server\Module::class,
            'tokenParamName' => 'accessToken',
            'tokenAccessLifetime' => 3600 * 24,
            'storageMap' => [
                'user_credentials' => 'app\models\User',
            ],
            'grantTypes' => [
                'user_credentials' => [
                    'class' => 'OAuth2\GrantType\UserCredentials',
                ],
                'refresh_token' => [
                    'class' => 'OAuth2\GrantType\RefreshToken',
                    'always_issue_new_refresh_token' => true
                ],
            ],
        ],
    ],

引导程序将初始化翻译并将所需的 URL 规则添加到 Yii::$app->urlManager

JWT 令牌

此分支不支持 JWT 令牌,请随时提交 (pull request)[https://github.com/roaresearch/yii2-oauth2-server/pulls] 以启用此功能。

UserCredentialsInterface

传递给 Yii::$app->user->identityClass 的类必须实现接口 \OAuth2\Storage\UserCredentialsInterface,以将 oauth2 凭据存储在用户表中。

use Yii;

class User extends common\models\User implements
    \OAuth2\Storage\UserCredentialsInterface
{

    /**
     * Implemented for Oauth2 Interface
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        /** @var \roaresearch\yii2\oauth2server\Module $module */
        $module = Yii::$app->getModule('oauth2');
        $token = $module->getServer()->getResourceController()->getToken();
        return !empty($token['user_id'])
            ? static::findIdentity($token['user_id'])
            : null;
    }

    /**
     * Implemented for Oauth2 Interface
     */
    public function checkUserCredentials($username, $password)
    {
        $user = static::findByUsername($username);
        if (empty($user)) {
            return false;
        }
        return $user->validatePassword($password);
    }

    /**
     * Implemented for Oauth2 Interface
     */
    public function getUserDetails($username)
    {
        $user = static::findByUsername($username);
        return ['user_id' => $user->getId()];
    }
}

迁移

下一步是运行迁移

yii migrate all -p=@roaresearch/yii2/oauth2server/migrations/tables
yii fixture "*" -n=roaresearch\\yii2\\oauth2server\\fixtures

第一个命令创建 OAuth2 数据库模式。第二个命令为 http://fake/ 插入测试客户端凭据 testclient:testpass

控制器

为了支持通过访问令牌进行认证,只需为您的控制器或模块添加行为即可。

use yii\{
    helpers\ArrayHelper,
    auth\HttpBearerAuth,
    filters\auth\QueryParamAuth,
};
use roasearch\yii2\oauth2server\filters\auth\CompositeAuth;

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 yii\helpers\ArrayHelper;
use roaresearch\yii2\oauth2server\filters\auth\CompositeAuth;

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

作用域

设置 roaresearch\yii2\oauth2server\filters\auth\CompositeAuth::$actionScopes 属性,指定哪些操作需要特定的作用域。如果作用域不满足,则操作不会执行,服务器将返回 HTTP 状态码 403。

public function behaviors()
{
    return ArrayHelper::merge(parent::behaviors(), [
        'authenticator' => [
            'class' => CompositeAuth::class,
            'actionScopes' => [
                'create' => 'default create',
                'update' => 'default edit',
                '*' => 'default', // wildcards are allowed
            ],
        ],,
    ]);
}

自动吊销令牌

有时需要在每次请求上吊销令牌,以防止请求被触发两次。

要启用此功能,需要在用于识别已认证用户的类中实现 roaresearch\yii2\oauth2server\RevokeAccessTokenInterface

use OAuth2\Storage\UserCredentialsInterface;
use roaresearch\yii2\oauth2server\{
    RevokeAccessTokenInterface,
    RevokeAccessTokenTrait,
};

class User extend \yii\db\ActiveRecord implement
    UserCredentialsInterface,
    RevokeAccessTokenInterface
{
    use RevokeAccessTokenTrait; // optional, trait with default implementation.

    // rest of the class.
}

然后使用此类作为 Yii::$app->user->identityClass 的配置

附加动作过滤器 roaresearch\yii2\oauth2server\filters\RevokeAccessToken 允许配置自动吊销访问令牌的操作。

public function behaviors()
{
    return [
        'revokeToken' => [
            'class' => \roaresearch\yii2\oauth2server\filters\RevokeAccessToken::class,
            // optional only revoke the token if it has any of the following
            // scopes. if not defined it will always revoke the token.
            'scopes' => ['author', 'seller'],
            // optional whether or not revoke all tokens or just the active one
            'revokeAll' => true,
            // optional if non authenticated users are permited.
            'allowGuests' => true,
            // which actions this behavior applies to.
            'only' => ['create', 'update'],
        ],
    ];
}

使用 JS 生成令牌

获取访问令牌(js 示例)

var url = window.location.host + "/oauth2/token";
var data = {
    'grant_type':'password',
    'username':'<some login from your user table>',
    'password':'<real pass>',
    'client_id':'testclient',
    'client_secret':'testpass'
};
//ajax POST `data` to `url` here
//

授权操作

用于为外部服务器生成访问代码的操作。首先运行提供的 fixtures 以将测试客户端加载到数据库中,以测试其使用。

composer run-fixtures

如果您使用的测试 URL 不在默认 URI 列表中,您将不得不修改数据库中 oauth_clients 表上的信息。

然后您可以通过访问 Yii2 URI 来测试访问代码生成

/WEB/authorize?client_id=testclient&response_type=code&state=xyz&redirect_uri=http://127.0.0.1:8080/

它必须显示一个包含仅 2 个按钮的最小表单,用于选择是否拒绝或授权。如果您授权,将生成新的访问代码并将重定向到

http://127.0.0.1:8080/?code=[access code]6&state=xyz

如果您拒绝访问,它将重定向到相同的URI并带有错误代码。

您可以使用类 roaresearch\yii2\oauth2server\actions\AuthorizeAction 在您想要的任何控制器中声明授权操作。

use roaresearch\yii2\oauth2server\actions\AuthorizeAction;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'authorize' => [
                'class' => AuthorizeAction::class,
                'loginUri' => ['site/login'],
                'viewRoute' => 'authorize',
                'oauth2Module' => 'api/oauth2',
            ],
        ];
    }
}

构建于

行为准则

请阅读CODE_OF_CONDUCT.md了解我们的行为准则详情。

贡献

请阅读CONTRIBUTING.md了解向我们的提交拉取请求的流程详情。

版本控制

我们使用SemVer进行版本控制。有关可用版本,请参阅此存储库的标签

关于版本控制规则9、10和11,SemVer讨论了预发布版本,它们将不会使用。

作者

还可以查看参与此项目的贡献者列表

许可证

本项目采用MIT许可证 - 有关详细信息,请参阅LICENSE.md文件。

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