首页 > 解决方案 > 我无法添加 3 个参数来使用 LexikJWTAuthenticationBundle 和 Symfony 进行身份验证和生成令牌

问题描述

我正在构建一个 REST API,我想再添加一个参数来验证令牌。默认使用用户名和密码,我需要添加第三个参数,但我的代码不起作用。我使用了以下示例:LexikJWTAuthenticationBundle---validating-data-in-the-jwt-payload

1.我在该文件夹中创建了文件夹“src\EventListener”和文件“JWTDecodedListener.php”。

2.然后,我在该文件中添加了以下内容:

<?php

namespace App\EventListener;

use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTDecodedEvent;

class JWTDecodedListener
{
    /**
     * @param JWTDecodedEvent $event
     *
     * @return void
     */
    public function onJWTDecoded(JWTDecodedEvent $event)
    {
        $request = $this->requestStack->getCurrentRequest();
        
        $payload = $event->getPayload();

        if (!isset($payload['contract']) || $payload['contract'] !== $request->getContract()) {
            $event->markAsInvalid();
        }
    }
}

3.我还在文件“\config\services.yaml”中插入了设置:

# config/services.yaml
services:
    acme_api.event.jwt_decoded_listener:
        class: App\EventListener\JWTDecodedListener
        arguments: [ '@request_stack' ]
        tags:
            - { name: kernel.event_listener, event: lexik_jwt_authentication.on_jwt_decoded, method: onJWTDecoded }

4.在邮递员上测试应用程序时,使用新字段发出请求“http://127.0.0.1:8000/api/login_check”,验证时不考虑合同字段。我这样做如下:

{
    "username":"9VJ203Q4A53DH8I",
    "roles":["ROLE_USER"],
    "contract": "1122334455",
    "password": "123456"
}

我的项目树如下所示: 在此处输入图像描述

我不知道缺少什么或我做错了什么。我希望仅当用户名、合同和密码正确时才返回令牌。

标签: jwtjwt-authsymfony5lexikjwtauthbundle

解决方案


推荐阅读