New in Symfony 6.4: Simpler Logout

Contributed by
Mathieu

in #50946.

In Symfony applications, the logout feature of the security system is enabled
and configured per firewall. You can configure it with YAML, XML or PHP, but the
following example only shows the YAML config:

# config/packages/security.yaml
security:
# …

firewalls:
main:
# …
logout:
path: app_logout

The key of this configuration is the path option, which defines the route/URL
that the user needs to browse to actually un-authenticate from the application.
Symfony handles this log out process entirely, but that route/URL must exist in
your application.

That’s why you need to add that route in your application. For example, you could
create this YAML route definition which doesn’t point to any controller action:

# config/routes.yaml
app_logout:
path: /logout
methods: GET

Or, if you prefer to define all routes in PHP classes via attributes, you could
do this:

// src/Controller/SecurityController.php
namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentRoutingAnnotationRoute;

class SecurityController extends AbstractController
{
#[Route(‚/logout‘, name: ‚app_logout‘, methods: [‚GET‘])]
public function logout(): never
{
// controller can be blank: it will never be called!
throw new Exception(‚Don’t forget to activate logout in security.yaml‘);
}
}

Creating this route always felt a bit quirky. If Symfony handles all the logout
logic, why not take care of this route too? In Symfony 6.4 we’re simplifying
the logout feature
to take care of this.

Technically, this works thanks to a custom route loader that creates the logout
routes for you. If your application uses Symfony Flex the needed configuration
will be added to your application automatically when you update the symfony/security-bundle
recipe. Otherwise, you’ll need to add this configuration to your application:

_security_logout:
resource: security.route_loader.logout
type: service

Sponsor the Symfony project.

Symfony Blog

Read More

Latest News

PHP-Releases

PHP 8.2.16 released!

PHP 8.3.3 released!

PHP 8.1.27 released!

Generated by Feedzy