Version: Symfony2.3
There is many link that shows how to login programmatically on Symfony or Changing user Roles dynamically on login. I referred some sites and got the code working.
Below the Process,
- User login with username and password
- User will be redirected to Group list page
- User will select one group
- We will change the Role mapped with the selected Group dynamically and redirect user
Every thing works fine.
But problem is: I am using below code to get user id in all Pages, is stop working after changing "Token"
$id = $this->getUser()->getId();
I have a function with dynamically change Current User role based on different Groups
// Save the original token in the session
$originalToken = $this->get("security.context")->getToken();
$this->getRequest()->getSession()->set('original.security.token', $originalToken);
// Create my new custom token (loading the roles of the user)
$token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken($this->getUser()->getUsername(), null, "secured_area", array($dynamic_rolename));
// Update the security context with the new token
$this->get("security.context")->setToken($token);
$this->get('session')->set('security_secured_area',serialize($token));
The line $this->getUser()->getId()
not working after the above function executed.
Error: FatalErrorException: Error: Call to a member function getId() on a non-object
Security.yml
security:
encoders:
Core\Bundle\Entity\login:
algorithm: sha1
encode_as_base64: false
iterations: 1
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
providers:
administrators:
entity:
class: Core\Bundle\Entity\login
property: userName
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/login$
security: false
anonymous: ~
context: administration
secured_area:
pattern: ^/
context: administration
form_login:
check_path: _security_check
login_path: /login
default_target_path: /admin/setfacility
logout:
path: _demo_logout
target: _demo
#anonymous: ~
#http_basic:
# realm: "Secured Demo Area"
Why the getUser() object not been set?