我正在构建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"
}
我的项目树如下所示: enter image description here
我不知道丢失了什么或做错了什么。我希望仅在用户名,合同和密码正确的情况下才返回令牌。