Search code examples
phpsymfonyimpersonation

Symfony impersonate a User and multiple firewall


I have a problem with a feature of symfony. When I impersonate a User and I make a call to my API the user is not the impersonate.

Here is my security config:

api:
    pattern:   ^/api/.*
    provider: fos_userbundle
    guard:
        authenticators:
            - app.wsse_authenticator
            - app.form_login_authenticator
        entry_point: app.wsse_authenticator
    logout:       true
    stateless: true
    anonymous:    true
    switch_user: true
    context: my_context
main:
    pattern:   ^/.*
    provider: fos_userbundle
    guard:
        authenticators:
            - app.form_login_authenticator
    switch_user: true
    logout:       true
    anonymous:    true
    remember_me:
        secret:      "%secret%"
        lifetime: 7200 # in seconds (=12h)
        always_remember_me: true
    context: my_context

I tried to use the same context to share the impersonate user between both firewall but it's not working.

When a make a request on /test the impersonate user is used but when I make a request on /api/test the user is me and not the impersonate.

Someone could help me?


Solution

  • I believe that what you're trying to do would not work the way you'd want it.

    The API firewall is stateless, which means that there is no session involved in the authentication. Usually with a REST API you send a TOKEN with your request via setting a header or as part of the request - http://localhost/api/users?apiKey=my_key_goes_here which is how you authenticate.

    On the other hand in the main firewall the authentication is done via a session. The authentication credentials (i.e. UserToken) are stored in the a session and then they are used each time the user makes a request to a url of your site.

    Having a context would have worked if both firewalls were session based. In this particular case the authentication methods are simply incompatible which is why you can't simply click on the Symfony development tool bar and impersonate another user.

    Doing a simple search in packagist I found SwitchUserStatelessBundle which might be what you're looking for.