I have two Symfony 7.1 projects – one provides an API (named "core" – uses API Platform v4 and JWT Lexik Bundle), the other is a web based front-end to access the data (named "dashboard"). Users login to the dashboard, which asks the core for a Json Web Token (JWT) via a HTTP request.
I understood that the JWT Lexik Bundle was aimed at being on the project that provides the API (core, in my case). However, I’m struggling to understand if there’s something I can have on the client side (dashboard, in my case) which helps to retrieve the JWT and convert it into a UserInterface
object that contains the roles etc.
Is this something is possible with a Symfony project, or should I manually retrieve the roles via another API call? Would using the Lexik bundle on both sides help?
Edit:
I’ve made some progress by installing the Lexik bundle in both apps and changing /config/packages/lexik_jwt_authentication.yaml
as follows:
lexik_jwt_authentication:
secret_key: '%env(resolve:JWT_SECRET_KEY)%'
public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
pass_phrase: '%env(JWT_PASSPHRASE)%'
token_extractors:
cookie:
enabled: true
name: 'jwt'
authorization_header:
enabled: false
When I then authenticate against my API manually and retrieve the JWT, I set this as a secure cookie. The Lexik bundle then is able to pick this cookie up because of the above config, and I can use the various Symfony functions to allow/deny access by role.
It seems that there may be a simpler way, but it’s working OK for the moment.
2
Answers
I am using Lexik to authenticate from tokens created by Auth0, which has a slightly different payload structure than Lexik’s own tokens, so I had to make a custom user class implementing JWTUserInterface, but your configuration should otherwise be pretty much the same.
Check the docs for database-less user provider. Something like this should work for you. In
config/packages/security.yaml
, tell Symfony to get its user information from Lexik:To authenticate with JWT and fetch a user object from an API in another project, follow these steps:
Obtain the JWT: Log in through the API and receive the token after providing valid credentials.
Include the JWT: Send the token in the Authorization header as Bearer <your_token> when calling the user-related endpoint.
Verify the Token: The API validates the JWT to ensure it’s legitimate and not expired.
Fetch the User Object: On successful verification, the API sends back the requested user object in the response.
This approach ensures secure data exchange while keeping your systems modular.