跳到内容

以编程方式创建 JWT 令牌

编辑此页

在许多情况下,手动为给定用户创建 JWT 令牌可能很有用,例如在通过邮件确认用户注册后。为此,请直接使用 lexik_jwt_authentication.jwt_manager 服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\User\UserInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;

class ApiController extends Controller
{
    public function getTokenUser(UserInterface $user, JWTTokenManagerInterface $JWTManager): JsonResponse
    {
        // ...

        return new JsonResponse(['token' => $JWTManager->create($user)]);
    }
}

这将触发 Events::JWT_CREATEDEvents::JWT_ENCODED 事件并返回 JWT 令牌,但 Events::AUTHENTICATION_SUCCESS 事件不会被触发,你需要自己创建和格式化响应。

对于手动验证用户身份并返回与登录表单相同的响应

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\User\UserInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Authentication\AuthenticationSuccessHandler;

class FooController extends Controller
{
    public function fooAction(AuthenticationSuccessHandler $authenticationSuccessHandler): JsonResponse
    {
        $user = ...; // Fetch user

        return $authenticationSuccessHandler->handleAuthenticationSuccess($user);
    }
}

你也可以将现有的 JWT 传递给 handleAuthenticationSuccess 方法

1
return $authenticationSuccessHandler->handleAuthenticationSuccess($user, $jwt);
这项工作,包括代码示例,均根据 Creative Commons BY-SA 3.0 许可协议获得许可。
目录
    版本