hosannahighertech/yii2-oauth2-server

此包已被废弃且不再维护。作者建议使用 https://github.com/rhertogh/yii2-oauth2-server 包代替。

PHP OAuth2 服务器,filsh/yii2-oauth2-server 的分支

v1.0.1 2018-06-15 07:57 UTC

This package is not auto-updated.

Last update: 2024-01-31 17:44:54 UTC


README

实现 OAuth2 服务器(https://github.com/bshaffer/oauth2-server-php)的包装器。这是对 https://github.com/Filsh/yii2-oauth2-server 的分支。由于原始仓库中分支问题长期未解决,我决定进行分支。无法保证两者将保持兼容,因此在过渡过程中请检查是否有任何问题。

安装

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

运行

php composer.phar require --prefer-dist hosannahighertech/yii2-oauth2-server "*"

或添加

"hosannahighertech/yii2-oauth2-server": "1.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
            ]
        ]
    ]
]

配置 User 类

common\models\User - 实现 \OAuth2\Storage\UserCredentialsInterface 接口的用户模型,因此 OAuth2 凭据数据存储在用户表中。请确保您实现了

  1. public function checkUserCredentials($username, $password),该函数检查提供的用户名和密码的有效性,如果用户名和密码有效则返回 TRUE,否则返回 FALSE。

  2. public function getUserDetails($username),该函数返回关联的 "user_id" 和可选的 "scope" 值的数组,例如

[ 
    "user_id"  => USER_ID,    // REQUIRED user_id to be stored with the authorization code or access token
    "scope"    => SCOPE       // OPTIONAL space-separated list of restricted scopes
] 

额外的 OAuth2 标志

enforceState - 标志,用于控制状态控制器是否允许在 "Authorization Code" 授权类型中使用 "state" 参数

allowImplicit - 标志,用于控制控制器是否允许 "implicit" 授权类型

下一步,您应该运行迁移

 yii migrate --migrationPath=@vendor/hosannahighertech/yii2-oauth2-server/migrations

此迁移创建 OAuth2 数据库模式并插入测试用户凭据 testclient:testpasshttp://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();
    }
}

有关请求和响应的更多信息,以及 OAuth 授权类型的说明,请参阅 Jenkov 的优秀教程:http://tutorials.jenkov.com/oauth2/

更多信息

另外,如果您设置 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

JWT 令牌

如果您想获取Json Web Token (JWT) 而不是传统令牌,您需要在模块中设置 'useJwtToken' => true,然后定义两个额外的配置:'public_key' => 'app\storage\PublicKeyStorage',这是实现 PublickKeyInterface 的类,以及 'access_token' => 'OAuth2\Storage\JwtAccessToken',它实现了 JwtAccessTokenInterface.php。Oauth2基本库提供了默认的 access_token,它工作得很好。只需使用它,一切都会顺利。

以下是一个实现 PublickKeyInterface 的示例类。请确保私钥和公钥的路径正确。您可以使用OpenSSL工具分两步生成它们(感谢(Rietta)[https://rietta.com/blog/2012/01/27/openssl-generating-rsa-key-from-command/])

  1. openssl genrsa -des3 -out privkey.pem 2048

  2. openssl rsa -in privkey.pem -outform PEM -pubout -out pubkey.pem

注意:您可以将文件的 内容复制并粘贴到类的变量中。这很丑陋,但如果您需要,它可以正常工作。

<?php
namespace app\security\storage;

class PublicKeyStorage implements \OAuth2\Storage\PublicKeyInterface{


    private $pbk =  null;
    private $pvk =  null; 

    public function __construct()
    {
        $pvkText =  file_get_contents(dirname(__FILE__).'/../keys/privkey.pem');        
        $this->pvk = openssl_get_privatekey($pvkText, 'YOUR_PASSPHRASE_IF_ANY');
        
        $this->pbk =  file_get_contents(dirname(__FILE__).'/../keys/pubkey.pem'); 
    }

    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 "RS256";
    }

}

更多内容请见 https://github.com/bshaffer/oauth2-server-php