davidxu/yii2-oauth2-server

Oauth2 服务器

安装: 5

依赖者: 0

建议者: 0

安全性: 0

星星: 0

关注者: 0

分支: 1

类型:yii2-extension

1.0.2 2024-09-14 04:48 UTC

This package is auto-updated.

Last update: 2024-09-14 04:49:16 UTC


README

https://github.com/davidxu/yii2-oauth2-server 分支而来,使用了https://github.com/samdark/yii2-league-oauth2-server的部分代码。

还受到了https://github.com/chervand/yii2-oauth2-server的启发。

安装

将以下内容添加到您的 composer.json

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

使用方法

步骤 1

您需要一些东西

  • 该模块需要使用一个 UserRepository 来获取用户。最简单的方法是使用现有的 User 类,并确保它还实现了以下接口

    • yii\web\IdentityInterface
    • League\OAuth2\Server\Entities\UserEntityInterface
    • League\OAuth2\Server\Repositories\UserRepositoryInterface
      • 确保在 UserRepositoryInterface::getUserEntityByUserCredentials()验证 用户

    还确保实现 findIdentityByAccessToken(),它被 davidxu\oauth2\components\authMethods\HttpBearerAuth 用于通过访问令牌进行用户认证。示例

    <?php
        /**
       * {@inheritdoc}
       */
      public static function findIdentityByAccessToken($token, $type = null) {
          return static::find()
              ->where(['user.status'=>static::STATUS_ACTIVE])
              ->leftJoin('{{%oauth_access_token}}', '`user`.`id` = `{{%oauth_access_token}}`.`user_id`')
              ->andWhere(['{{%oauth_access_token}}.identifier' => $token])
              ->one();
      }

    然后,将 User 类作为配置数组中的属性 $userRepository 传递,如下所示。

  • SSH 密钥对。请参阅 https://oauth2.thephpleague.com/installation/

$ openssl genrsa -out private.key 2048
$ openssl rsa -in private.key -pubout -out public.key

确保生成的密钥文件的文件权限为 600 或 660。

  • 加密密钥(一个随机字符串)

  • 迁移文件

$ php yii migrate --migrationPath=@vendor/davidxu/yii2-oauth2-server/migrations

步骤 2

将其作为 yii2 模块添加

<?php
$config = [
 'modules' => [
        'oauth2' => [
            'class' => davidxu\oauth2\Module::class,
            'userRepository' => \app\models\User::class,
            'privateKey' => '@common/data/keys/private.key',
            'publicKey' => '@common/data/keys/public.key',
            'encryptionKey' => 'put-a-nice-random-string-here',
        ],
    ],
];
?>

还将模块添加到应用程序的 bootstrap

...
'bootstrap' => ['log','api.v1',...,'oauth2'],
...

配置

目前还没有太多配置。或许将来有一天可用的授权类型将会是动态的。

访问控制(保护 API 调用)

检查客户端凭据

因为客户端凭据方法创建的访问令牌没有与特定用户关联,所以它使用不同的过滤器来检查令牌的有效性。

davidxu\oauth2\components\filters\CheckClientCredentials 添加到您的行为中,以验证客户端凭据访问密钥。

其他认证流程

davidxu\oauth2\components\authMethods\HttpBearerAuth 添加到您的行为中,例如

<?php
 public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => HttpBearerAuth::class,
        ];
        $behaviors['contentNegotiator'] = [
            'class' => 'yii\filters\ContentNegotiator',
            'formats' => [
                'application/json' => Response::FORMAT_JSON,
            ]
        ];

        return $behaviors;
    }

yiisoft/yii2-authclient(或类似的授权代码授予客户端)一起使用

创建一个自定义客户端,以下是一些 URL

  • 授权 URL: <domain>/oauth2/authorize
  • 令牌 URL: <domain>/oauth2/token/create