Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logout from http_basic auth in Symfony2

Whenever I go to /admin/logout, I'm correctly redirected to the root of my project but still logged in when I visit /admin/ as I'm not prompted for credentials.

Here is my configuration:

security.yml

security:
    firewalls:
        admin_area:
            pattern:    ^/admin
            http_basic: ~
            stateless:  true
            switch_user: { role: ROLE_SUPER_ADMIN, parameter: _want_to_be_this_user }
            logout: { path: /admin/logout, target: / }

AdminBundle/Resources/config/routing.yml

logout:
    pattern:   /logout

app/config/routing.yml

admin:
    resource: "@AdminBundle/Resources/config/routing.yml"
    prefix:   /admin

The authorization is still in place as the headers state Authorization:Basic YWRtaW46cEAkJHcwUmQh so I guess credentials are still provided to the application during the request.

I know there is no proper way to logout from a HTTP Basic Auth as per this question but maybe Symfony2 allows it?

like image 445
D4V1D Avatar asked Mar 24 '15 09:03

D4V1D


Video Answer


1 Answers

Once logged in via http auth, your browser will cache and add your login credentials to each subsequent request in the form of a header like this:

Authorization:Basic YWRtaW46YWRtaW4=

When you do a logout, the next request to the server will still hold your http credentials and log you in again.

So the trick is to lose the http credentials on the client side after destroying the session on the server side.

In the past there where some hackidy methods like submitting false credentials or some obscure IE method for deleting the cache. But I don't think these methods still work.

What still works ( I tested the following method with symfony 2.7 and google chrome 45 ) is replying to the client with a HTTP 401 unauthorized response.

Check it out:

Add the following to your logout section in the app/config/security.yml file

logout:
    success_handler: logout_listener

To your services configuration app/config/services.yml

logout_listener:
    class: AppBundle\LogoutListener

Then create a listener that responds with HTTP 401 unauthorized

<?php 

namespace AppBundle;

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

class LogoutListener implements  LogoutSuccessHandlerInterface 
{
    public function onLogoutSuccess(Request $request) 
    {
        return new Response('', 401);
    }
}

After logging out your app will send a 401 to the browser which will think authentication has failed resulting in the auth cache being cleared ( who wants to remember faulty credentials anyway right ) and prompt for your credentials again

like image 139
Niki Van Cleemput Avatar answered Oct 14 '22 10:10

Niki Van Cleemput