minhhoit / oauth2
Yii2框架的Oauth2服务器扩展
dev-master
2016-09-26 06:25 UTC
Requires
- yiisoft/yii2: >=2.0.4
This package is not auto-updated.
Last update: 2024-09-18 19:18:13 UTC
README
此扩展使用Yii2实现了OAuth 2.0规范。
安装
安装此扩展的最佳方式是通过composer。
要安装,请运行以下命令之一
$ php composer.phar require minhhoit/oauth2 "*"
或
"minhhoit/oauth2": "*"
将以下内容添加到您的composer.json
文件的require
部分。
要创建数据库表,请运行迁移命令
$ yii migrate --migrationPath=@minhhoit/oauth2/migrations
用法
OAuth 2.0授权使用
namespace app\controllers; use app\models\LoginForm; class AuthController extends \yii\web\Controller { public function behaviors() { return [ /** * Checks oauth2 credentions and try to perform OAuth2 authorization on logged user. * AuthorizeFilter uses session to store incoming oauth2 request, so * you can do additional steps, such as third party oauth authorization (Facebook, Google ...) */ 'oauth2Auth' => [ 'class' => \minhhoit\oauth2\AuthorizeFilter::className(), 'only' => ['index'], ], ]; } public function actions() { return [ /** * Returns an access token. */ 'token' => [ 'class' => \minhhoit\oauth2\TokenAction::classname(), ], /** * OPTIONAL * Third party oauth providers also can be used. */ 'back' => [ 'class' => \yii\authclient\AuthAction::className(), 'successCallback' => [$this, 'successCallback'], ], ]; } /** * Display login form, signup or something else. * AuthClients such as Google also may be used */ public function actionIndex() { $model = new LoginForm(); if ($model->load(\Yii::$app->request->post()) && $model->login()) { if ($this->isOauthRequest) { $this->finishAuthorization(); } else { return $this->goBack(); } } else { return $this->render('index', [ 'model' => $model, ]); } } /** * OPTIONAL * Third party oauth callback sample * @param OAuth2 $client */ public function successCallback($client) { switch ($client::className()) { case GoogleOAuth::className(): // Do login with automatic signup break; ... default: break; } /** * If user is logged on, redirects to oauth client with success, * or redirects error with Access Denied */ if ($this->isOauthRequest) { $this->finishAuthorization(); } } }
API控制器示例
class ApiController extends \yii\rest\Controller { public function behaviors() { return [ /** * Performs authorization by token */ 'tokenAuth' => [ 'class' => \minhhoit\oauth2\TokenAuth::className(), ], ]; } /** * Returns username and email */ public function actionIndex() { $user = \Yii::$app->user->identity; return [ 'username' => $user->username, 'email' => $user->email, ]; } }
客户端配置示例
return [ ... 'components' => [ 'authClientCollection' => [ 'class' => 'yii\authclient\Collection', 'clients' => [ 'myserver' => [ 'class' => 'yii\authclient\OAuth2', 'clientId' => 'unique client_id', 'clientSecret' => 'client_secret', 'tokenUrl' => 'http://127.0.0.1/auth/token', 'authUrl' => 'http://127.0.0.1/auth/index', 'apiBaseUrl' => 'http://127.0.0.1/api', ], ], ], ];
许可协议
conquer/oauth2采用MIT许可协议发布。有关详细信息,请参阅捆绑的LICENSE
文件。