SebScoFr
SebScoFr

Reputation: 901

Symfony2 - Authentication lost after redirection

I've been experiencing an issue with my SF2 application today. I want the user to be automatically authenticated after submiting a valid subscription form.

So basically in my controller here's what I do:

if ($form->isValid()) {
    $customer = $form->getData();

    try {
        $customer = $this->get('my.service.manager.customer')->customerSubscribe($customer);
    } catch (APIClientException $e) {
        $error = $e->getErrors();
        ...
    }

    if ($customer && !isset($error)) {
        // connect customer
        $token = new UsernamePasswordToken($customer, null, 'api_auth', array('ROLE_USER'));
        $this->get('security.context')->setToken($token);

        ...
    }

    return new RedirectResponse($this->generateUrl('MyBundle_index'));
}

The two lines below the 'connect customer' comment actually seem to authenticate the user fine. The problem being when I redirect to another page with RedirectResponse, then the authentication is lost.

I've tried a call to

$this->container->get('security.context')->isGranted('ROLE_USER')

which returns true just before the call to RedirectResponse, and false in my other controller where the response is being redirected.

At this point I'm a bit confused about what I'm doing wrong. Any ideas appreciated. Btw, I'm using Symfony2.1

Upvotes: 0

Views: 1537

Answers (2)

SebScoFr
SebScoFr

Reputation: 901

Ok I solved it like so:

$token = new UsernamePasswordToken($customer->getEmail(), null, 'api_auth', array('ROLE_USER'));

Apparently I needed to pass the customer id (in that case the email) as the first argument of UsernamePasswordToken, instead of the entire customer object. I'm not sure why since my entity Customer has a _toString method implemented, but at least it works fine like that.

Upvotes: 1

Thomas Kelley
Thomas Kelley

Reputation: 10292

I've noticed this happens when you redirect more than once at a time. Does the controller for the MyBundle_index route return another redirect? If so, I think that's your answer.

Otherwise, maybe try using forwards? Instead of:

return new RedirectResponse($this->generateUrl('MyBundle_index'));

...just forward to whatever controller/action is defined for that route:

return $this->forward("SomeBundle:Default:index");

The URL that the user ends up with in their address bar might not be what you're expecting (it won't change from the one they requested originally), but you can probably fiddle with that to get it to your liking.

Upvotes: 1

Related Questions