7

I want to force a user to logout in symfony2 after checking that it has not enough capabilities for access into a specific secured area.

I've tried with :

$this->get('request')->getSession()->invalidate();

but it seems that something goes wrong, the user still logged in until I logged him out using /logout route.

I've to mention that I'm using KayueWordpressBundle to connect my symfony app with a wordpress based website to create a custom back office.

Here is my security.yml file

security:
firewalls:
    dev:
        pattern:  ^/(_(profiler|wdt)|css|images|js)/
        security: false
    login_firewall:
        pattern:    ^/$
        anonymous:  ~
    secured_area:
        pattern:    ^/
        kayue_wordpress: ~
        form_login:
            check_path: /login_check
            login_path: /
        logout:
            path:   /logout
            target: /
access_control:
    - { path: ^/admin, roles: ROLE_ADMIN }

providers:
    wordpress:
        entity: { class: Kayue\WordpressBundle\Entity\User, property: username }

encoders:
    Kayue\WordpressBundle\Entity\User:
        id: kayue_wordpress.security.encoder.phpass

How can I do this please ?

Thank you

1

1 Answer 1

20

You can force logout by calling setToken() with null, try something like this:

$this->container->get('security.context')->setToken(null);

It will destroy user token from the security context and kick the user out.


Also, please see this question for more details: Symfony2: how to log user out manually in controller?

Sign up to request clarification or add additional context in comments.

3 Comments

above given solution will not call logout handler, if i have registered any handler for logout.
BTW, use $this->container->get('security.authorization_checker') instead (new in 2.6)
@Ronan, it's $this->container->get('security.token_storage'). See New in Symfony 2.6: Security component improvements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.