How to return the token AND the user after successful login in Symfony 6 using LexikJWTAuthenticationBundle

Viewed 504

I am using Symfony 6 and LexikJWTAuthenticationBundle. After successful login, I get back a token but I would also like it to return the user.

This is the response I get right now:

$ curl -X POST -H "Content-Type: application/json" http://localhost/api/login_check -d '{"username":"martin","password":"123"}'

Response:
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...."}

But I would like it to include the authenticated user in the response like this, but I cannot find anywhere a way to enable this.

{
  "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE2NDk4NjkxNzQsImV4cCI6MTY0OTg3Mjc3NCwicm9sZXMiOlsiUk9MRV9VU0VSIl0sInVzZXJuYW1lI....."
  "user": { id: 1, username: 'martin', password: '123' }
}

Here is how my security.yaml looks like:

security:
    enable_authenticator_manager: true
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
        App\Entity\User:
            algorithm: auto

    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User
                property: username
    firewalls:
        login:
            pattern: ^/api/login
            stateless: true
            provider: app_user_provider
            json_login:
                check_path: /api/login_check
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure

        api:
            pattern: ^/api
            stateless: true
            jwt: ~

    access_control:
        - { path: ^/api/login,       roles: PUBLIC_ACCESS }
        - { path: ^/api,             roles: IS_AUTHENTICATED_FULLY }

when@test:
    security:
        password_hashers:
            Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
                algorithm: auto
                cost: 4 # Lowest possible value for bcrypt
                time_cost: 3 # Lowest possible value for argon
                memory_cost: 10 # Lowest possible value for argon
1 Answers

You need to implement a custom "success_handler".

security:
  firewalls:
    login:
      json_login:
        success_handler: YOUR_CUSTOM_SUCCESS_HANDLER_SERVICE

The easiest way is to extend the "Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Authentication\AuthenticationSuccessHandler" class and to overwrite the "handleAuthenticationSuccess" method.

Otherwise, if you only need to update the response data:

Listen for the "Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent" and update the data there.

Related