alegz / yii2-oauth2-server
PHP框架Yii2的OAuth2服务器
Requires
This package is not auto-updated.
Last update: 2024-09-18 20:28:15 UTC
README
实现OAuth2服务器的包装器(https://github.com/bshaffer/oauth2-server-php)
重要
这是原始(https://github.com/Filsh/yii2-oauth2-server)仓库的分支,也作为一个独立的包提交,但保留了代码命名空间。
原因是原始仓库长时间没有更新。我和我的朋友们应用了一些有用的补丁,进行了修复和改进。修复了分支混乱的问题。最新稳定版本现在在master分支。请查看已关闭的拉取请求,以了解更多对master所做的更改(https://github.com/Alegzander/yii2-oauth2-server/pulls?q=is%3Apr+is%3Aclosed)
安装
通过composer安装此扩展是首选方式。
运行以下命令之一
php composer.phar require --prefer-dist alegz/yii2-oauth2-server "*"
或
"alegz/yii2-oauth2-server": "~2.0"
将以下内容添加到composer.json的require部分。
要使用此扩展,只需在您的应用程序配置中添加以下代码,作为一个新的模块
'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 ] ] ] ]
如果您想获取Json Web Token (JWT)而不是传统令牌,您需要在模块中设置'useJwtToken' => true
,然后定义两个更多配置:'public_key' => 'app\storage\PublicKeyStorage'
,这是一个实现PublickKeyInterface的类,以及'access_token' => 'app\storage\JwtAccessToken'
,这是一个实现JwtAccessTokenInterface.php的类
common\models\User
- 用户模型,实现了一个接口 \OAuth2\Storage\UserCredentialsInterface
,因此OAuth2凭据数据存储在用户表中。对于Oauth2基本库提供了默认的访问令牌,它工作得很好,除了它试图在数据库中保存令牌。所以我决定从它继承,并覆盖尝试保存的部分(令牌大小太大,与数据库中的VARCHAR(40)冲突)。
TL;DR,以下是一些示例类 access_token
<?php namespace app\storage; /** * * @author Stefano Mtangoo <mwinjilisti at gmail dot com> */ class JwtAccessToken extends \OAuth2\Storage\JwtAccessToken { public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = null) { } public function unsetAccessToken($access_token) { } }
和 public_key
<?php namespace app\storage; class PublicKeyStorage implements \OAuth2\Storage\PublicKeyInterface{ private $pbk = null; private $pvk = null; public function __construct() { //files should be in same directory as this file //keys can be generated using OpenSSL tool with command: /* private key: openssl genrsa -out privkey.pem 2048 public key: openssl rsa -in privkey.pem -pubout -out pubkey.pem */ $this->pbk = file_get_contents('privkey.pem', true); $this->pvk = file_get_contents('pubkey.pem', true); } public function getPublicKey($client_id = null){ return $this->pbk; } public function getPrivateKey($client_id = null){ return $this->pvk; } public function getEncryptionAlgorithm($client_id = null){ return 'HS256'; } }
注意:您需要应用此 PR 或您可以通过检查此差异自行修补。PR的其余部分仅适用于您想使用firebase JWT库(但这不是强制性的)。
同时,扩展common\models\User
- 用户模型,实现接口 \OAuth2\Storage\UserCredentialsInterface
,因此OAuth2凭据数据存储在用户表中。您应该实现
- findIdentityByAccessToken()
- checkUserCredentials()
- getUserDetails()
您可以根据需要扩展模型(请记住更新配置文件)
use Yii;
class User extends common\models\User implements \OAuth2\Storage\UserCredentialsInterface
{
/**
* Implemented for Oauth2 Interface
*/
public static function findIdentityByAccessToken($token, $type = null)
{
/** @var \filsh\yii2\oauth2server\Module $module */
$module = Yii::$app->getModule('oauth2');
$token = $module->getServer()->getResourceController()->getToken();
return !empty($token['user_id'])
? static::findIdentity($token['user_id'])
: null;
}
/**
* Implemented for Oauth2 Interface
*/
public function checkUserCredentials($username, $password)
{
$user = static::findByUsername($username);
if (empty($user)) {
return false;
}
return $user->validatePassword($password);
}
/**
* Implemented for Oauth2 Interface
*/
public function getUserDetails($username)
{
$user = static::findByUsername($username);
return ['user_id' => $user->getId()];
}
}
额外的OAuth2标志
enforceState
- 开关标志,使状态控制器允许在“授权码”授权类型中使用“state”参数
allowImplicit
- 开关标志,使控制器允许“隐式”授权类型
下一步,您应该运行迁移
yii migrate --migrationPath=@vendor/filsh/yii2-oauth2-server/migrations
此迁移创建oauth2数据库模式和插入测试用户凭据 testclient:testpass
为 http://fake/
将url规则添加到urlManager
'urlManager' => [ 'enablePrettyUrl' => true, //only if you want to use petty URLs '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
,则可以使用隐式授权类型 - 了解更多
请求示例
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
如果您想获取Json Web Token (JWT)而不是传统令牌,您需要在模块中设置'useJwtToken' => true
,然后定义两个更多配置:'public_key' => 'app\storage\PublicKeyStorage'
,这是一个实现PublickKeyInterface的类,以及'access_token' => 'app\storage\JwtAccessToken'
,这是一个实现JwtAccessTokenInterface.php的类
对于Oauth2基库默认提供了 访问令牌,它非常好用,除了它尝试将令牌保存到数据库中。因此,我决定继承它并覆盖尝试保存的部分(令牌大小太大,在数据库中的VARCHAR(40)崩溃。
TL;DR,以下是一些示例类 access_token
<?php namespace app\storage; /** * * @author Stefano Mtangoo <mwinjilisti at gmail dot com> */ class JwtAccessToken extends \OAuth2\Storage\JwtAccessToken { public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = null) { } public function unsetAccessToken($access_token) { } }
和 public_key
<?php namespace app\storage; class PublicKeyStorage implements \OAuth2\Storage\PublicKeyInterface{ private $pbk = null; private $pvk = null; public function __construct() { //files should be in same directory as this file //keys can be generated using OpenSSL tool with command: /* private key: openssl genrsa -out privkey.pem 2048 public key: openssl rsa -in privkey.pem -pubout -out pubkey.pem */ $this->pbk = file_get_contents('privkey.pem', true); $this->pvk = file_get_contents('pubkey.pem', true); } public function getPublicKey($client_id = null){ return $this->pbk; } public function getPrivateKey($client_id = null){ return $this->pvk; } public function getEncryptionAlgorithm($client_id = null){ return 'HS256'; } }
获取访问令牌(JavaScript示例)
var url = window.location.host + "/oauth2/token"; var data = { 'grant_type':'password', 'username':'<some login from your user table>', 'password':'<real pass>', 'client_id':'testclient', 'client_secret':'testpass' }; //ajax POST `data` to `url` here //
获取访问令牌(JavaScript示例)
var url = window.location.host + "/oauth2/token"; var data = { 'grant_type':'password', 'username':'<some login from your user table>', 'password':'<real pass>', 'client_id':'testclient', 'client_secret':'testpass' }; //ajax POST `data` to `url` here //