Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best place to store JWT data to be available in Controllers

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading