longthanhtran / yii2-oauth2-server
Yii2 OAuth2 授权服务器
1.2.0
2021-09-17 10:30 UTC
Requires
- php: >=7.4 || ^8.0
- ext-json: *
- andreyv/yii2-ip-ratelimiter: ^2.3
- guzzlehttp/guzzle: ^7.3
- lcobucci/jwt: ^4.1
- league/oauth2-server: ^8.3
- nesbot/carbon: ^2.52
- yiisoft/yii2: ~2.0.14
- yiisoft/yii2-twig: ^2.4
This package is auto-updated.
Last update: 2024-09-17 16:26:42 UTC
README
安装
composer require longthanhtran/yii2-oauth2-server
注意
-
该包作为 Yii2 模块,用于执行 OAuth2 授权服务器的主要功能。它基于 league/oauth2-server,可以在 PHP 7.4 或 8.0 上运行。
-
示例模块配置:请检查
config
文件夹中名为 modules.php 的文件。然后,在 @app/config/web.php 中直接在 $params 键后面追加'modules' => $modules,
。
use longthanhtran\oauth2\Module; use League\OAuth2\Server\Grant\AuthCodeGrant; use League\OAuth2\Server\Grant\ClientCredentialsGrant; use League\OAuth2\Server\Grant\PasswordGrant; use League\OAuth2\Server\Grant\RefreshTokenGrant; return [ 'oauth2' => [ 'class' => 'longthanhtran\oauth2\Module', 'privateKey' => __DIR__ . '/../keys/private.key', 'publicKey' => __DIR__ . '/../keys/public.key', 'encryptionKey' => "you-need-to-prepare-this-encryption-key", 'enableGrantTypes' => function(Module $module) { $server = $module->authorizationServer; // Client Credentials Grant $server->enableGrantType( new ClientCredentialsGrant(), new DateInterval('PT1H') // expires after 1 hour ); // Authorization Code Grant $authCodeGrant = new AuthCodeGrant( $module->authCodeRepository, $module->refreshTokenRepository, new DateInterval('PT10M') // expires after 10 minutes ); $authCodeGrant->setRefreshTokenTTL( new DateInterval('P1M') // expires after 1 month ); $server->enableGrantType( $authCodeGrant, new DateInterval('PT1H') // expires after 1 hour ); // Refresh Token Grant $refreshTokenGrant = new RefreshTokenGrant( $module->refreshTokenRepository ); $refreshTokenGrant->setRefreshTokenTTL( new DateInterval('P1M') // expires after 1 month ); $server->enableGrantType( $refreshTokenGrant, new DateInterval('PT1H') // expires after 1 hour ); // Password Grant - legacy grant $passwordGrant = new PasswordGrant( $module->userRepository, $module->refreshTokenRepository ); $passwordGrant->setRefreshTokenTTL(new DateInterval('P1M')); $server->enableGrantType( $passwordGrant, new DateInterval('PT1H') // expires after 1 hour ); } ] ];
请确保准备好 privateKey
、publicKey
(位于 @app/keys 文件夹中)和加密密钥。您可以通过参考 Yii2 指南中的加密指南来了解 encryptionKey
。
- 要准备模式,请运行以下迁移:
yii migrate --migrationPath=@vendor/longthanhtran/yii2-oauth2-server/oauth2/migrations
- 为了验证用户的凭据,您可以为您自己的 User 类实现 UserEntityInterface,以下是一个示例。请确保在
User
中使用use UserQueryTrait
。
namespace app\models; use League\OAuth2\Server\Entities\ClientEntityInterface; trait UserQueryTrait { public function getUserEntityByUserCredentials($username, $password, $grantType, ClientEntityInterface $clientEntity) { $user = User::findOne(['username' => $username]); if ($user && $user->validatePassword($password)) { return $user; } return null; } }