繁体   English   中英

如何在 JWT 中使用 CakePHP3“身份验证”插件

[英]How to use CakePHP3 "Authentication" Plugin with JWT

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

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

我的配置:

  • PHP 7.2.19

  • MySQL 5.7.27

  • 阿帕奇 2.4.29

  • 蛋糕PHP 3.8

  • 身份验证插件 1.1

  • 火力基地/ php-jwt

我按照指南配置,并在 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 之前尝试一个带有 CORS 错误的 OPTIONS 请求。

我的 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));
}

如果说明书有一个完整的令牌认证示例,那可能不会有什么坏处。

也可以看看

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM