Skip to content

Instantly share code, notes, and snippets.

@thibaut-decherit
Last active October 9, 2024 19:33
Show Gist options
  • Save thibaut-decherit/5b4e7a256ec6e38603e015d99108215f to your computer and use it in GitHub Desktop.
Save thibaut-decherit/5b4e7a256ec6e38603e015d99108215f to your computer and use it in GitHub Desktop.
Symfony - Logout with CSRF protection

URL version (GET)

config/packages/security.yaml

security:
  firewalls:
    main:
      logout:
        path: logout
        csrf_parameter: token
        csrf_token_generator: security.csrf.token_manager

example.html.twig

<a href="{{ path('logout', {'token' : csrf_token('logout')}) }}">Logout</a>

Button version (POST)

config/packages/security.yaml

security:
  firewalls:
    main:
      logout:
        path: logout
        csrf_token_generator: security.csrf.token_manager

example.html.twig

<form action="{{ path('logout') }}" method="post" id="form-button-logout">
    <input type="hidden" name="_csrf_token" value="{{ csrf_token('logout') }}" id="csrf-token"/>
    <input
            class="btn btn-danger border-0 rounded-0 text-white" type="submit" id="_submit"
            name="_submit"
            value="Logout"
    />
</form>
@mshannaq
Copy link

mshannaq commented Sep 4, 2024

you can use

$this->security->logout(false)

to programmatically log out without checking for a valid CSRF token , see https://github.com/symfony/security-bundle/blob/5e10107856ff64d477c61fed7bcbb8a16125ea01/Security.php#L114

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment