heihei / yii2-oauth2-server

为 Yii 框架提供的 PHP 5.6+ Oauth2 服务器集成

安装: 43

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 18

类型:yii2-extension

2.0.0 2017-08-31 10:06 UTC

This package is not auto-updated.

Last update: 2024-09-17 16:21:25 UTC


README

此扩展允许开发者使用 Oauth2 服务器。

Latest Stable Version Build Status License

Latest Development Version Build Status composer.lock

安装

如果您使用 Packagist 安装软件包,则可以像这样更新您的 composer.json

{
    "require": {
        "heihei/yii2-oauth2-server": "~2.0.0"
    }
}

如何使用它

将扩展添加到您的配置中

return [
    //....
    'bootstrap' => [
        //....
        'oauth2',
        //....
    ],
    'modules' => [
        //....
        'oauth2' => [
            'class' => 'sweelix\oauth2\server\Module',
            'backend' => 'redis',
            'db' => 'redis',
            'identityClass' => 'app\models\User', // only if you don't want to use the user identityClass
            //
            // Parameters
            //
        ],
        //....
    ],
    //....
];

配置模块

基本模块参数

  • backend : 目前只能为 redis
  • db : redis 组件或连接或连接配置的 ID
  • identityClass : 用于连接 oauth2 授权系统的用户类,默认为用户组件的 identityClass
  • webUserParamId : 允许主应用用户(会话)和模块应用用户分离,默认为 __oauth2
  • identityCookieName : 允许主应用用户(cookie)和模块应用用户分离,默认为 oauth2
  • webUser : 允许完全管理模块 Web 用户,默认为 []
  • baseEndPoint : 令牌和授权端点的基路径,默认为 ''
  • overrideLayout : 覆盖模块布局以使用另一个布局(例如:@app/views/layouts/oauth2)
  • overrideViewPath : 覆盖视图路径以使用特定的视图路径(例如:@app/views/oauth2)

授权管理

  • allowImplicit : 允许隐式授权(默认为 false
  • allowAuthorizationCode : 允许授权码授权(默认为 true
  • allowClientCredentials : 允许客户端凭据授权(默认为 true
  • allowPassword : 允许用户凭据/密码授权(默认为 true
  • allowCredentialsInRequestBody : 允许在请求体中包含凭据(默认为 true
  • allowPublicClients : 允许公开客户端(默认为 true
  • alwaysIssueNewRefreshToken : 总是颁发新的刷新令牌(默认为 true
  • unsetRefreshTokenAfterUse : 使用后清除刷新令牌(默认为 true

JWT 参数

  • allowJwtAccessToken : 启用 JWT(默认:false
  • allowAlgorithm : JWT 可用的算法(默认:['RS256', 'RS384', 'RS512']
  • jwtAudience : 默认为令牌端点
  • storeEncryptedTokenString : 存储加密的令牌(默认:true

生存时间(TTL)

  • idTTL : ID 令牌的 TTL(默认为 3600
  • accessTokenTTL : 访问令牌的 TTL(默认为 3600
  • refreshTokenTTL : 刷新令牌的 TTL(默认为 14 * 24 * 3600

基本 OAuth 名称

  • realm : Realm 值(默认为 Service
  • tokenQueryName : 访问令牌参数的名称(默认为 access_token
  • tokenBearerName : 授权头的名称(默认为 Bearer

强制参数

  • enforceState : 强制状态参数(默认为 true
  • allowOnlyRedirectUri : 需要确切的重定向 URI(默认为 true

OpenID

  • allowOpenIdConnect : 启用 openId connect(默认:false)// 尚未实现

授权码参数

  • enforceRedirect : 强制重定向参数(默认为 false
  • authorizationCodeTTL : 授权码的TTL(默认为 30

CORS

  • cors : 在令牌端点上启用 CORS(默认:false) CORS部分可以使用数组定义,具体请参阅 Yii 文档
 return [
     //....
     'bootstrap' => [
         //....
         'oauth2',
         //....
     ],
     'modules' => [
         //....
         'oauth2' => [
             'class' => 'sweelix\oauth2\server\Module',
             'backend' => 'redis',
             'db' => 'redis',
             'identityClass' => 'app\models\User', // only if you don't want to use the user identityClass
             //
             // Cors parameters example :
             //
             'cors' => [
                'Origin' => ['https://www.myowndomain.com'],
             ]
         ],
         //....
     ],
     //....
 ];

用户身份和Web用户

配置用户组件以链接OAuth2系统和用户/身份管理

return [
    //....
    'components' => [
        //....
        'user' => [
            'class' => 'sweelix\oauth2\server\web\User',
            'identityClass' => 'app\models\User', // Identity class must implement UserModelInterface
            //
            // Parameters
            //
        ],
        //....
    ],
    //....
];

IdentityClass 必须实现 sweelix\oauth2\server\interfaces\UserModelInterface。您可以使用 sweelix\oauth2\server\traits\IdentityTrait 特性来自动实现

  • public function getRestrictedScopes()
  • public function setRestrictedScopes($scopes)
  • public static function findIdentityByAccessToken($token, $type = null)

您需要实现剩余的方法

  • public static function findByUsernameAndPassword($username, $password)
  • public static function findByUsername($username)

为OAuth2创建特定视图

为了使用自己的视图(而不是内置视图),您可以覆盖

  • layout:模块参数 overrideLayout
  • viewPath:模块参数 overrideViewPath

覆盖布局

您应该创建一个经典布局,例如

<?php
/**
 * @app/views/layouts/newLayout.php
 * @var string $content
 */
use yii\helpers\Html;

$this->beginPage(); ?>
    <!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title><?php echo Html::encode($this->title); ?></title>

        <meta name="viewport" content="width=device-width, initial-scale=1">

        <?php $this->head(); ?>
    </head>
    <body>
        <?php $this->beginBody(); ?>
            <?php echo $content;?>
        <?php $this->endBody(); ?>
    </body>

</html>
<?php $this->endPage();

并将其链接到模块

return [
    //....
    'modules' => [
        //....
        'oauth2' => [
            'class' => 'sweelix\oauth2\server\Module',
            'overrideLayout' => '@app/views/layouts/newLayout',
            //
            // Additional Parameters
            //
        ],
        //....
    ],
    //....
];

覆盖视图

您应该创建3个视图,以允许OAuth2模块按预期工作,并将它们链接到模块

return [
    //....
    'modules' => [
        //....
        'oauth2' => [
            'class' => 'sweelix\oauth2\server\Module',
            // use views in folder oauth2
            'overrideViewPath' => '@app/views/oauth2',
            //
            // Additional Parameters
            //
        ],
        //....
    ],
    //....
];

错误视图

此视图用于在发生错误时显示页面

<?php
/**
 * error.php
 *
 * @var string $type error type
 * @var string $description error description
 */
use yii\helpers\Html;
?>

    <h1 class="alert-heading"><?php echo ($type ? : 'Unkown error'); ?></h1>
    <p><?php echo ($description ? : 'Please check your request'); ?></p>

登录视图

此视图用于在需要时显示登录页面

<?php
/**
 * login.php
 *
 * @var \sweelix\oauth2\server\forms\User $user
 *
 */
use yii\helpers\Html;
?>
    <?php echo Html::beginForm('', 'post', ['novalidate' => 'novalidate']); ?>
        <label>Username</label>
        <?php echo Html::activeTextInput($user, 'username', [
            'required' => 'required',
        ]); ?>
        <br/>
    
        <label>Password</label>
        <?php echo Html::activePasswordInput($user, 'password', [
            'required' => 'required',
        ]); ?>
        <br/>
        <button type="submit">LOGIN</button>
    <?php echo Html::endForm(); ?>

授权视图

此视图用于在需要时显示授权页面

<?php
/**
 * authorize.php
 *
 * @var \sweelix\oauth2\server\interfaces\ScopeModelInterface[] $requestedScopes
 * @var \sweelix\oauth2\server\interfaces\ClientModelInterface $client
 *
 */
use yii\helpers\Html;
?>
    <h1><?php echo $client->name ?> <span>requests access</span></h1>
    
    <?php echo Html::beginForm(); ?>
        <?php if(empty($requestedScopes) === false) : ?>
        <ul>
            <?php foreach($requestedScopes as $scope): ?>
            <li>
                <h4><?php echo $scope->id; ?></h4>
                <p>
                    <?php echo $scope->definition; ?>
                </p>
            </li>
            <?php endforeach; ?>
        </ul>
        <?php endif; ?>
            <!-- name of decline button **must be** decline -->
            <button type="submit" name="decline">DECLINE</button>
            <!-- name of accept button **must be** accept -->
            <button type="submit" name="accept">AUTHORIZE</button>
    <?php echo Html::endForm(); ?>

公开模型概述

Oauth2 Yii2 扩展公开了多个模型,这些模型可用于您的应用程序。所有模型都可以使用 Yii2 DI 进行覆盖。

例如,如果您想覆盖 Client 模型,您必须使用以下方式在 DI 中注入自己的模型

Yii::$container->set('sweelix\oauth2\server\interfaces\ClientModelInterface', [
    'class' => YourClientModel::className(),
]);

Client / ClientModelInterface

  • Client::findOne($id) - 通过ID查找客户端
  • Client::findAllByUserId($id) - 通过用户ID查找所有用户接受的客户端
  • $client->save() - 保存客户端
  • $client->delete() - 删除客户端
  • $client->hasUser($userId) - 检查用户(用户ID)是否已接受客户端
  • $client->addUser($userId) - 将用户(用户ID)附加到客户端
  • $client->removeUser($userId) - 从客户端断开用户(用户ID)的连接

AccessToken / AccessTokenModelInterface

  • AccessToken::findOne($id) - 通过ID查找accessToken
  • AccessToken::findAllByUserId($id) - 为用户(userId)查找所有accessToken
  • AccessToken::findAllByClientId($id) - 为客户端(clientId)查找所有accessToken
  • AccessToken::deleteAllByUserId($id) - 删除用户(userId)的所有accessToken
  • AccessToken::deleteAllByClientId($id) - 删除客户端(clientId)的所有accessToken
  • $accessToken->save() - 保存accessToken
  • $accessToken->delete() - 删除accessToken

RefreshToken / RefreshTokenModelInterface

  • RefreshToken::findOne($id) - 通过ID查找accessToken
  • RefreshToken::findAllByUserId($id) - 为用户(userId)查找所有refreshTokens
  • RefreshToken::findAllByClientId($id) - 为客户端(clientId)查找所有refreshTokens
  • RefreshToken::deleteAllByUserId($id) - 删除用户(userId)的所有refreshTokens
  • RefreshToken::deleteAllByClientId($id) - 删除客户端(clientId)的所有refreshTokens
  • $refreshToken->save() - 保存refreshToken
  • $refreshToken->delete() - 删除refreshToken

AuthCode / AuthCodeModelInterface

  • AuthCode::findOne($id) - 通过ID查找authCode
  • $authCode->save() - 保存authCode
  • $authCode->delete() - 删除authCode

Scope / ScopeModelInterface

  • Scope::findOne($id) - 通过ID查找scope
  • Scope::findAvailableScopeIds() - 查找所有scope IDs
  • Scope::findDefaultScopeIds() - 查找默认scope IDs
  • $scope->save() - 保存作用域
  • $scope->delete() - 删除作用域

CypherKey / CypherKeyModelInterface

  • CypherKey::findOne($id) - 通过ID查找CypherKey
  • $cypherKey->save() - 保存CypherKey
  • $cypherKey->delete() - 删除CypherKey
  • $cypherKey->generateKeys() - 为当前CypherKey生成随机密钥

关联RBAC和作用域系统

使用sweelix\oauth2\server\web\User类将自动关联rbac系统和oauth2系统。

权限系统将进行轻微修改以允许细粒度检查

  • Yii::$app->user->can('read')将检查

    1. 当前客户端是否允许read作用域
    2. 当前用户是否允许rbac权限read
  • Yii::$app->user->can('rbac:read')将仅检查当前用户是否允许rbac权限read

  • Yii::$app->user->can('oauth2:read')将仅检查当前客户端是否允许read作用域

运行测试

在运行测试之前,您应编辑文件tests/config/redis.php,并将配置更改为与您的环境匹配。

命令行界面(CLI)系统

提供了一些命令来管理oauth2系统

  • php protected/yii.php oauth2:client/create
  • php protected/yii.php oauth2:client/update
  • php protected/yii.php oauth2:key/create
  • php protected/yii.php oauth2:scope/create