Home > Blockchain >  Efficient way to access JWT data from Controllers
Efficient way to access JWT data from Controllers

Time:03-26

I'm using Symfony 5.4 with a custom authenticator which reads & validates a JWT with each request.

Inside the JWT is data which I need accessible in the controller.

Rather than re-read the JWT in the controller, I'd like to store the decoded data, or even 1 element of that data, so that it doesn't need to be re-read in a controller.

What is an efficient way to access data detected in an authenticator, so it is available in the context of a controller action?

CodePudding user response:

I would implement service for this in Symfony, which should be something like this

<?php

namespace App\Service;

use Symfony\Component\HttpFoundation\RequestStack;

class JWTInterceptor
{
    protected $request;

    protected $data;

    public function __construct(RequestStack $requestStack)
    {
        $this->request = $requestStack->getCurrentRequest();
        // Get JWT token from request header, decode and store it in $this->data
    }

    // Get decoded data
    public function getData()
    {
        return $this->data;
    }
}

And in your controller just use Dependency Injection to insert the service and call JWTInterceptor::getData() to use decoded data.

There should be other approach as well, like using EventListener or EventSubscriber or implement a root/base controller with relevant methods and make it accessible to all child controllers etc.

Or if you are using https://github.com/lexik/LexikJWTAuthenticationBundle it already comes packaged with events so you can modify as per your need.

  • Related