Search code examples
apireact-nativesymfony4api-platform.comlexikjwtauthbundle

Add a logout action with symfony 4 and Api platform and use this action with React Native to destroy the token generated by JWT


I use symfony 4 with Api platform and jwt bundle to manage user authentication with token. I want to add a logout action to logout user from the front app and destroy the token and redirect to login screen ( front with React Native). My configuration in the security.yml :

security:
    encoders:
        App\Entity\AppUser:
            algorithm: auto
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\AppUser
                property: email
        # used to reload user from session & other features (e.g. switch_user)
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            stateless: true
            anonymous: true
            provider: app_user_provider
            json_login:
                check_path: /authentication_token
                username_path: email
                password_path: password
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator
            logout:
                path: app_logout
        refresh:
            pattern:  ^/token/refresh
            stateless: true
            anonymous: true

            # activate different ways to authenticate
            # https://symfony.com/doc/current/security.html#firewalls-authentication

            # https://symfony.com/doc/current/security/impersonating_user.html
            # switch_user: true

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        - { path: ^/token/refresh, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/docs, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/generate_token, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, roles: IS_AUTHENTICATED_FULLY }

I created a securityController.php and i added the logout action like this :

<?php


namespace App\Controller;


use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class SecurityController extends AbstractController
{
    /**
     * @Route("/logout", name="app_logout", methods={"GET"})
     */
    public function logout()
    {
        throw new \Exception('should not be reached');
    }
}

I created a function in my front app like this :

logoutAndDestroyToken() {
    axios.get(API.partage_mandats_local + '/logout', { headers: { 'Authorization': 'Bearer ' + this.props.token } })
      .then((response) => {
        console.log(response.data)
        this.props.navigation.navigate('Dashboard')
      })
      .catch((error) => {
        console.log('Error' + error)
      })
  }

but i received a strange object as response. The response of axios function is :

{
    "@context": "/contexts/Entrypoint",
    "@id": "/",
    "@type": "Entrypoint",
    "mandateRequest": "/mandate_requests",
    "contactProject": "/contact_projects",
    "contactRequest": "/contact_requests",
    "tradeOperationType": "/trade_operation_types",
    "requestStatus": "/request_statuses",
    "city": "/cities",
    "contactType": "/contact_types",
    "contact": "/contacts",
    "contactRequestCommission": "/contact_request_commissions",
    "appUser": "/app_users",
    "mandate": "/mandates"
}

What i need is to logout and destroy the token. Any suggestions please ?


Solution

  • you can simply delete the token you stored on the client-side (e.i. browser, local storage). and for more security, you should invalidate the token from server-side, this link can be useful for understanding the scenario.