gowravshekar / yii2-oauth2-server
PHP的OAuth2服务器
Requires
This package is not auto-updated.
Last update: 2024-09-14 18:52:54 UTC
README
实现OAuth2服务器的一个包装器(https://github.com/bshaffer/oauth2-server-php)
安装
安装此扩展的首选方式是通过 composer。
运行以下命令之一:
php composer.phar require --prefer-dist filsh/yii2-oauth2-server "*"
或添加
"filsh/yii2-oauth2-server": "~2.0"
到您的composer.json文件的要求部分。
要使用此扩展,只需在您的应用程序配置中添加以下代码
'bootstrap' => ['oauth2'], 'modules' => [ 'oauth2' => [ 'class' => 'filsh\yii2\oauth2server\Module', 'tokenParamName' => 'accessToken', 'tokenAccessLifetime' => 3600 * 24, 'storageMap' => [ 'user_credentials' => 'common\models\User', ], 'grantTypes' => [ '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凭证数据存储在用户表中
额外的OAuth2标志
enforceState
- 当状态控制器允许使用“state”参数在“授权码”授予类型中时,该标志会切换
allowImplicit
- 当控制器允许使用“implicit”授予类型时,该标志会切换
下一步,您应该运行迁移
yii migrate --migrationPath=@vendor/filsh/yii2-oauth2-server/migrations
此迁移创建OAuth2数据库模式和插入测试用户凭证 testclient:testpass
用于 http://fake/
添加到urlManager的URL规则
'urlManager' => [ 'rules' => [ 'POST oauth2/<action:\w+>' => 'oauth2/rest/<action>', ... ] ]
用法
要使用此扩展,只需添加基控制器的行为
use yii\helpers\ArrayHelper; use yii\filters\auth\HttpBearerAuth; use yii\filters\auth\QueryParamAuth; use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter; use filsh\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://api.mysite.com/authorize?response_type=code&client_id=TestClient&redirect_uri=https://fake/
/** * SiteController */ class SiteController extends Controller { /** * @return mixed */ public function actionAuthorize() { if (Yii::$app->getUser()->getIsGuest()) return $this->redirect('login'); /** @var $module \filsh\yii2\oauth2server\Module */ $module = Yii::$app->getModule('oauth2'); $response = $module->handleAuthorizeRequest(!Yii::$app->getUser()->getIsGuest(), Yii::$app->getUser()->getId()); /** @var object $response \OAuth2\Response */ Yii::$app->getResponse()->format = \yii\web\Response::FORMAT_JSON; return $response->getParameters(); } }
如果您将 allowImplicit => true
设置为true,则可以使用隐式授予类型 - 查看更多
请求示例
https://api.mysite.com/authorize?response_type=token&client_id=TestClient&redirect_uri=https://fake/cb
带有重定向响应
https://fake/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=bearer&expires_in=3600