elstc/cakephp-oauth-server

CakePHP 3 的 OAuth 服务端,使用 PHP League 的 OAuth2 服务端

v0.8.7 2024-04-04 07:48 UTC

README

Software License Build Status

这是一个用于在 CakePHP 3 中实现 OAuth2 服务端的插件。基于 PHP League 的 OAuth2 服务端 构建。目前我们支持以下授权类型:AuthCode、RefreshToken、ClientCredentials。

该存储库是 uafrica/oauth-server 的分支。

要求

  • PHP >= 7.1,并启用 openssl 扩展
  • CakePHP >= 3.5
  • 数据库(已测试 MySQL、SQLite)

安装

您可以使用以下命令将此插件安装到 CakePHP 应用程序中。运行

composer require elstc/cakephp-oauth-server

加载插件

(CakePHP >= 3.6.0) 通过在项目的 src/Application.php 文件中添加以下语句来加载插件

$this->addPlugin('OAuthServer');

(CakePHP <= 3.5.x) 通过在项目的 config/bootstrap.php 文件中添加以下语句来加载插件

Plugin::load('OAuthServer', ['bootstrap' => true, 'route' => true]);

运行数据库迁移

需要运行数据库迁移。

bin/cake migrations migrate -p OAuthServer

生成和设置密钥

生成 私有和公开密钥(也请参阅 https://oauth2.thephpleague.com/installation/

openssl genrsa -out config/oauth.pem 2048
openssl rsa -in config/oauth.pem -pubout -out config/oauth.pub

生成 加密密钥

vendor/bin/generate-defuse-key
(COPY result hash)

修改您的 app.php,添加 OAuthServer 配置

    'OAuthServer' => [
        'privateKey' => CONFIG . 'oauth.pem',
        'publicKey' => CONFIG . 'oauth.pub',
        'encryptionKey' => 'def0000060c80a6856e8...', // <- SET encryption key FROM `vendor/bin/generate-defuse-key`
    ],

注意:私有密钥和加密密钥是机密的。尽可能多地使用环境变量设置,不要上传到源代码仓库。

对于 Apache HTTP 服务器 + php-fpm 或 php-cgi

在 Apache HTTP 服务器中使用 php-fpm 时,授权头不透明。因此需要一些设置。

将以下语句添加到 webroot/.htaccess 中

# Apache HTTP Server 2.4.13 and later and use mod_proxy / mod_proxy_fcgi
CGIPassAuth on

# Apache HTTP Server 2.4.12 and older
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

并在您的应用程序上应用 \OAuthServer\Middleware\AuthorizationEnvironmentMiddleware

class Application extends BaseApplication
{
    public function middleware($middleware)
    {
        $middleware
            ->add(ErrorHandlerMiddleware::class)

            ->add(AssetMiddleware::class)

            // ADD THIS: bypass Authorization environment to request header
            ->add(\OAuthServer\Middleware\AuthorizationEnvironmentMiddleware::class)

            ->add(RoutingMiddleware::class);

        return $middleware;
    }
}

建议在 AssetMiddleware 和 RoutingMiddleware 之间插入。

配置

假设您已经使用内置的 CakePHP 3 认证组件实现了基于表单的认证。如果没有,请参阅 认证章节

将 OAuthServer 设置为认证适配器。

在您的 AppController::beforeFilter() 方法中添加(或修改)

$this->Auth->config('authenticate', [
    'Form',
    'OAuthServer.OAuth'
]);

修改您的登录方法如下

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);

            $redirectUri = $this->Auth->redirectUrl();
            if ($this->request->getQuery('redir') === 'oauth') {
                $redirectUri = [
                    'plugin' => 'OAuthServer',
                    'controller' => 'OAuth',
                    'action' => 'authorize',
                    '?' => $this->request->getQueryParams(),
                ];
            }

            return $this->redirect($redirectUri);
        } else {
            $this->Flash->error(
                __('Username or password is incorrect'),
                'default',
                [],
                'auth'
            );
        }
    }
}

或者,如果您使用的是 Friends Of Cake CRUD 插件,请添加

'login' => [
    'className' => 'OAuthServer.Login'
]

到您的 CRUD 动作配置中。

使用

OAuth2 基础路径为 example.com/oauth

为了添加客户端和 OAuth 范围,您需要创建一个 ClientsController 和一个 ScopesController(这些不是本插件的一部分)

最简单的方法是使用 Friends Of Cake CRUD-View 插件

通过运行以下命令安装它

$ composer require friendsofcake/bootstrap-ui:dev-master
$ composer require friendsofcake/crud:dev-master
$ composer require friendsofcake/crud-view:dev-master

然后创建一个看起来像这样的 ClientsController

<?php
namespace App\Controller;

use Crud\Controller\ControllerTrait;

/**
 * OauthClients Controller
 *
 * @property \OAuthServer\Model\Table\OauthClientsTable $Clients
 */
class ClientsController extends AppController
{

    use ControllerTrait;

    public $modelClass = 'OAuthServer.Clients';

    /**
     * @return void
     */
    public function initialize()
    {
        parent::initialize();
        $this->viewClass = 'CrudView\View\CrudView';
        $tables = [
            'Clients',
            'Scopes'
        ];
        $this->loadComponent('Crud.Crud', [
            'actions' => [
                'index' => [
                    'className' => 'Crud.Index',
                    'scaffold' => [
                        'tables' => $tables
                    ]
                ],
                'view' => [
                    'className' => 'Crud.View',
                    'scaffold' => [
                        'tables' => $tables
                    ]
                ],
                'edit' => [
                    'className' => 'Crud.Edit',
                    'scaffold' => [
                        'tables' => $tables,
                        'fields' => [
                            'name',
                            'redirect_uri',
                            'parent_model',
                            'parent_id' => [
                                'label' => 'Parent ID',
                                'type' => 'text'
                            ]
                        ]
                    ]
                ],
                'add' => [
                    'className' => 'Crud.Add',
                    'scaffold' => [
                        'tables' => $tables,
                        'fields' => [
                            'name',
                            'redirect_uri',
                            'parent_model',
                            'parent_id' => [
                                'label' => 'Parent ID',
                                'type' => 'text'
                            ]
                        ]
                    ]
                ],
                'delete' => [
                    'className' => 'Crud.Delete',
                    'scaffold' => [
                        'tables' => $tables
                    ]
                ],
            ],
            'listeners' => [
                'CrudView.View',
                'Crud.RelatedModels',
                'Crud.Redirect',
                'Crud.Api'
            ],
        ]);
    }
}

以及一个看起来像这样的 ScopesController

<?php
namespace App\Controller;

use Crud\Controller\ControllerTrait;

/**
 * Scopes Controller
 *
 * @property \OAuthServer\Model\Table\OauthScopesTable $Scopes
 */
class ScopesController extends AppController
{

    use ControllerTrait;

    public $modelClass = 'OAuthServer.Scopes';

    /**
     * @return void
     */
    public function initialize()
    {
        parent::initialize();
        $this->viewClass = 'CrudView\View\CrudView';
        $tables = [
            'Clients',
            'Scopes'
        ];
        $this->loadComponent('Crud.Crud', [
            'actions' => [
                'index' => [
                    'className' => 'Crud.Index',
                    'scaffold' => [
                        'tables' => $tables
                    ]
                ],
                'view' => [
                    'className' => 'Crud.View',
                    'scaffold' => [
                        'tables' => $tables
                    ]
                ],
                'edit' => [
                    'className' => 'Crud.Edit',
                    'scaffold' => [
                        'tables' => $tables,
                        'fields' => [
                            'id' => [
                                'label' => 'ID',
                                'type' => 'text'
                            ],
                            'description',
                        ]
                    ]
                ],
                'add' => [
                    'className' => 'Crud.Add',
                    'scaffold' => [
                        'tables' => $tables,
                        'fields' => [
                            'id' => [
                                'label' => 'ID',
                                'type' => 'text'
                            ],
                            'description',
                        ]
                    ]
                ],
                'delete' => [
                    'className' => 'Crud.Delete',
                    'scaffold' => [
                        'tables' => $tables
                    ]
                ],
            ],
            'listeners' => [
                'CrudView.View',
                'Crud.RelatedModels',
                'Crud.Redirect',
            ],
        ]);
    }
}

自定义

OAuth2 服务端可以自定义,通过在 Template/Plugin/OAuthServer/OAuth 中创建模板来更改各个页面的外观

服务器还会触发一些事件,可以用于在过程中注入值。当前触发的事件包括

  • OAuthServer.beforeAuthorize - 在渲染用户授权页面时。
  • OAuthServer.afterAuthorize - 用户授权客户端时。
  • OAuthServer.afterDeny - 用户拒绝客户端时。

您可以通过在src/Template/Plugin/OAuthServer/OAuth/authorize.ctp中创建覆盖模板文件来自定义OAuth授权页面。

组件/认证器选项

  • OAuthServer.privateKey

必需:设置您的私钥文件路径。

密钥文件不应该被其他用户读取。(文件权限为 400440600640660

  • OAuthServer.publicKey

必需:设置您的公钥文件路径。该公钥由上面的私钥生成。

密钥文件不应该被其他用户读取。(文件权限为 400440600640660

  • OAuthServer.encryptionKey

必需:设置您的加密密钥字符串。该密钥由vendor/bin/generate-defuse-key命令生成。

  • OAuthServer.accessTokenTTL

可选:设置访问令牌TTL。指定一个可以被DateInterval类解析的格式。

默认:PT1H(1小时)

  • OAuthServer.refreshTokenTTL

可选:设置刷新令牌TTL。指定一个可以被DateInterval类解析的格式。

默认:P1M(1个月)

  • OAuthServer.authCodeTTL

可选:设置授权代码TTL。指定一个可以被DateInterval类解析的格式。

默认:PT10M(10分钟)

  • OAuthServer.supportedGrants

可选:设置支持的授权类型。此选项可以是以下列表之一:AuthCodeRefreshTokenClientCredentialsPassword

默认:['AuthCode', 'RefreshToken', 'ClientCredentials', 'Password']

  • OAuthServer.passwordAuthenticator

可选:设置使用密码授权的认证器。如果您的应用程序使用非默认认证器,请设置此选项。

默认:Form

OAuthAuthenticate 选项

  • continue

可选:如果设置为 true,如果 OAuth 认证失败,则不停止处理。当您只想使用认证信息而不需要登录时使用此选项。

默认:false

  • fields.username

可选:指定用户的键字段。

默认:id

更多配置选项请参阅:https://book.cakephp.com.cn/3.0/en/controllers/components/authentication.html#configuring-authentication-handlers