dmstr/yii2-oauth-module

1.0.2 2023-03-13 08:25 UTC

This package is auto-updated.

Last update: 2024-09-13 11:42:37 UTC


README

该包为 Yii 2.0 提供了一个模块,允许您使用 OAuth 2.0 进行身份验证。它基于 league/oauth2-client 包。

特性

  • 客户端凭证授权
  • 管理客户端的行政模块
  • 客户端的用户 ID 属性
  • 访问令牌加密
  • 访问令牌发行者
  • JWT 格式的访问令牌

安装

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

composer require dmstr/yii2-oauth-module

设置

将模块添加到您的 Web 应用程序配置中

<?php

use dmstr\oauth\Module as OAuthModule;
use dmstr\oauth\modules\admin\Module as OAuthAdminModule;

return [
    'modules' => [
        'oauth' => [
            'class' => OAuthModule::class,
            'tokenPrivateKey' => 'file:///path/to/private.key', // Path to private key file
            'tokenEncryptionKey' => 'your-secret', // optional. Only needed if you have a passphrase for your private key
            'accessTokenIssuer' => 'http://localhost:80', // Issuer of the access token.
            'userIdAttribute' => 'id', // The attribute of the user model that will be added to the access token as the `sub` claim.
            // This is optional but recommended. It will allow you to manage your clients in the admin interface.
            'modules' => [
                'admin' => [
                    'class' => OAuthAdminModule::class
                ]
            ]
        ]
    ],
    // This is only needed if your using codemix/yii2-localeurls (https://github.com/codemix/yii2-localeurls)
    'components' => [
        'urlManager' => [
            'ignoreLanguageUrlPatterns' => [
                '#^oauth/token#' => '#^oauth/token#'
            ]
        ],
        'rules' => [
            // This is only needed if you want to use the admin module. It will create an url alias to the user module
            'oauth/admin/user/index' => 'user/admin/index',
            'oauth/admin/user/view' => 'user/admin/update'
        ]
     
    ]
];

并将其添加到控制台应用程序配置中

[
    'controllerMap' => [
        'migrate' => [
            'migrationPath' => [
                '@vendor/dmstr/yii2-oauth-module/src/migrations'
            ]
        ]
    ]
]

或者运行

yii migrate/up --migrationPath=@vendor/dmstr/yii2-oauth-module/src/migrations

通用用法

首先,您需要生成一对公钥和私钥。您可以使用以下命令生成密钥对

openssl genrsa -out private.key 2048

如果您想为您的私钥提供密码,请运行此命令代替

openssl genrsa -aes128 -passout pass:<your-passphrase> -out private.key 2048

安装模块后,

然后您需要创建一个客户端。您可以通过 <your-base-url>/oauth/admin/client/index 访达管理客户端 CRUD。

您可以选择向客户端添加用户 ID。这将允许您在身份验证后使用客户端以该用户身份登录。如果不添加用户 ID,客户端将能够访问 API,但不能登录。用户 ID 添加到访问令牌中的 sub 断言。

要获取新的访问令牌,您可以发送 POST 请求到以下端点

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "grant_type=client_credentials&client_id=<your-client-id>&client_secret=<your-client-secret>" <your-base-url>/oauth/token

这将返回您请求认证所需的所有 必要信息

现在,您可以使用访问令牌来认证您的请求。

与 Yii 2.0 REST API 的示例用法

此示例展示了如何使用访问令牌在 Yii 2.0 REST API 中进行请求认证。它使用 bizley/yii2-jwt 包来认证请求。

<?php

namespace app\api\controllers;

use Da\User\Model\User;
use bizley\jwt\JwtHttpBearerAuth;
use yii\filters\AccessControl;
use yii\rest\Controller;

class ItemsController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator']['authMethods'] = [
            [
                'class' => JwtHttpBearerAuth::class,
                // We used auth() here to keep the example simple. Implementing findIdentityByAccessToken() in your user model is recommended.
                'auth' => function (Plain $token) {
                    return User::findIdentity($token->claims()->get('sub'));
                }
            ]
        ];
        $behaviors['access'] = [
            'class' => AccessControl::class,
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['@'],
                    'actions' => ['index']
                ]
            ]
        ];
        return $behaviors;
    }

    /**
     * Example action. Replace with your own.
     */
    public function actionIndex(): array
    {
        return [
            [
                'id' => 1,
                'name' => 'Item 1'
            ]
        ];
    }
}