如何在 JWT 中使用 CakePHP3 "Authentication" 插件

How to use CakePHP3 "Authentication" Plugin with JWT

我已经安装了 CakePhp 3.8,我需要使用 JWT 身份验证。

我已经尝试安装和配置 CakePHP/Authentication (https://book.cakephp.org/authentication/1.1/en/index.html) 但无法配置它。

我的配置:

我按照指南配置,并添加在AppController.php

// /src/Controller/Appcontroller.php
 public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Authentication.Authentication', [
            'logoutRedirect' => '/administrators/login'  // Default is false
        ]);
....

在Application.php

// /src/application.php
class Application extends BaseApplication implements AuthenticationServiceProviderInterface

....

public function getAuthenticationService(ServerRequestInterface $request, ResponseInterface $response)
    {
        $service = new AuthenticationService();
        $service->loadIdentifier('Authentication.JwtSubject');
        $service->loadAuthenticator('Authentication.Jwt', [
            'returnPayload' => false
        ]);
        return $service;
    }

....

public function middleware($middlewareQueue)
    {
....

        // Add the authentication middleware
        $authentication = new AuthenticationMiddleware($this);

        // Add the middleware to the middleware queue
        $middlewareQueue->add($authentication);

        return $middlewareQueue;
    }

我如何才能首次登录并检索 JWT 令牌?

--------------------编辑--------------------

谢谢,您的解决方案非常有效。

但是现在我遇到 Angular FE GET 请求的 CORS 问题,在 GET 之前尝试一个 OPTIONS 请求,但出现 CORS 错误。

我的 AppController 中有这个 CORS 策略

        // Accepted all CORS
        $this->response = $this->response->cors($this->request)
            ->allowOrigin(['*'])
            ->allowMethods(['GET','POST','PUT','DELETE','OPTIONS','PATCH']) // edit this with more method
            ->allowHeaders(['X-CSRF-Token']) //csrf protection for cors
            ->allowCredentials()
            ->exposeHeaders(['Link'])
            ->maxAge(60)
            ->build();

您必须自己处理,即创建一个处理登录请求的端点,并在身份验证成功后创建一个包含所需标识符的 JWT 令牌。

例如,对于 username/password 身份验证,您可以使用 Form 身份验证器和 Password 标识符:

$service->loadIdentifier('Authentication.Password');
$service->loadIdentifier('Authentication.JwtSubject');

$service->loadAuthenticator('Authentication.Form', [
    'loginUrl' => '/users/login'
]);
$service->loadAuthenticator('Authentication.Jwt', [
    'returnPayload' => false
]);

使用 UsersController 中的示例创建一个这样的 login() 操作(这只是一个非常基本的,希望不言自明的示例),检查身份验证状态,如果有效则生成令牌,如果无效生成错误:

public function login()
{
    if ($this->Authentication->getResult()->isValid()) {
        $userId = $this->Authentication->getIdentityData('id');
        $token = \Firebase\JWT\JWT::encode(
            ['sub' => $userId],
            \Cake\Utility\Security::getSalt()
        );

        $status = 200;
        $response = [
            'token' => $token,
        ];
    } else {
        $status = 403;
        $response = [
            'error' => 'Authentication required',
        ];
    }

    return $this
        ->getResponse()
        ->withStatus($status)
        ->withType('json')
        ->withStringBody(json_encode($response));
}

如果食谱中有令牌身份验证的完整示例,可能不会有什么坏处。

另见