Untitled
Untitled

Reputation: 790

symfony not recognizing an authenticated user

I am trying to implement a login page with symfony2 and for that I am using my own custom user provider.

The problem is when the user enters his credentials, he will not be recognized. By that, I mean the debug bar at the bottom says "You are not authenticated." and $request->getUser() will return null. But the strange thing is that the user will still be allowed to visit the pages that need him to log in.

I don't think the problem is with the authentication, since when I enter a wrong password, I get warned about it, but when I enter the correct one, I get redirected to the first page (but it still says "You are not authenticated.")

Do you know where I should be looking for the problem?

I have attached my security.yml file in this pastebin and routing.yml in this one.
Here is the code for my custom user provider.
And This is the User class definition.

EDIT: Here is the var_dump of my get('security.context')->getToken(). The funny thing is that authenticated is true, but getUser() is still null and the debug bar says I am not authenticated.

object(Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken)#46 (6) {
  ["credentials":"Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken":private]=>
  NULL
  ["providerKey":"Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken":private]=>
  string(11) "system_area"
  ["user":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
  NULL
  ["roles":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
  array(2) {
    [0]=>
    object(Symfony\Component\Security\Core\Role\Role)#45 (1) {
      ["role":"Symfony\Component\Security\Core\Role\Role":private]=>
      string(10) "ROLE_ADMIN"
    }
    [1]=>
    object(Symfony\Component\Security\Core\Role\Role)#44 (1) {
      ["role":"Symfony\Component\Security\Core\Role\Role":private]=>
      string(9) "ROLE_USER"
    }
  }
  ["authenticated":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
  bool(true)
  ["attributes":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
  array(0) {
  }
}

Upvotes: 2

Views: 2933

Answers (2)

Untitled
Untitled

Reputation: 790

I managed to fix the problem. It was because of the dummy code I had used in place of serialization of User objects. I replaced it with real code and problem was gone.

Upvotes: 1

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52513

In order to get the current User you have to use:

$this->get('security.context')->getToken()->getUser();

In order to check if the current User has a certain role use:

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

Upvotes: 2

Related Questions