How To Response Json in Symfony Logout Controller

Server Environment

1
2
3
4
5
6
7
8
9
$ cat /etc/issue
Ubuntu 16.04.2 LTS \n \l

$ cat composer.json
"require": {
"php": ">=5.5.9",
"symfony/symfony": "2.8.*",
...
},


Logout action can be performed by symfony2 security controller by default. when we give the path Logout like this it works fine. but I need to return some json format data in response to the javascript request.By default, it is a jump to the page to log out.

Define new rule for logout action app/config/security.yml

1
2
3
4
5
security:
...
logout:
path: /api/v1/logout
success_handler: "app.webservice_logout_success_listener"

A new service to response after logout app/config/services.yml

1
2
3
app.webservice_logout_success_listener:
class: AppBundle\Security\LogoutSuccessListener
arguments: []

Extend logout success handler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
/**
* Created by PhpStorm.
* User: liyuliang
* Date: 01/08/2018
* Time: 01:17 PM
*/

namespace AppBundle\Security;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;

/**
* Class LogoutSuccessListener
* @package AppBundle\Security
*/
class LogoutSuccessListener implements LogoutSuccessHandlerInterface
{
/**
* Creates a Response object to send upon a successful logout.
*
* @param Request $request
* @return Response never null
*/
public function onLogoutSuccess(Request $request)
{
// Do something to clear user information or logging
return new JsonResponse(["success" => true]);
}
}


Now, whenever a user goes to the logout route, at the end of that request, Symfony will automatically log the user out and then redirect them… all after the controller is ever executed.

By the way, there are a few other things that you can customize under the logout section, like where to redirect. You can find those options in the Symfony reference section.

Thank you for reading.
This post is copyrighted by Liyuliang’s Blog.
If reproduced, please indicate the source: Liyuliang’s Blog
This blog uses Creative Commons Attribution-NonCommercial-Share-Sharing 4.0 International License Agreement to license.


Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×