![](/img/trans.png)
[英]how to add user roles dynamically upon login with symfony2 (and fosUserBundle)?
[英]Getting the ROLES of the user after logging in with FOSUserBundle Symfony2
我在獲取已登錄用戶的角色時遇到問題。我嘗試覆蓋SecurityController並使用以下代碼:
public function loginAction(Request $request)
{
$userManager = $this->get('fos_user.user_manager');
$userId = $this->get('security.context')->getToken()->getUser()->getId();
$user = $userManager->findUserBy(array('id'=>$userId));
if( $user->hasRole('ROLE_ADMIN') && $this->get('security.context')->isGranted('IS_AUTHENTICATED_ANONYMOUSLY') ){
return new RedirectResponse($this->generateUrl('adminpage'));
}
if($user->hasRole('ROLE_ACCOUNTING') && $this->get('security.context')->isGranted('IS_AUTHENTICATED_ANONYMOUSLY') ){
return new RedirectResponse($this->generateUrl('accountingpage'));
}
....
這里的問題是getId()會引發如下錯誤:
錯誤:在字符串上調用成員函數getId()
我用下面的代碼嘗試了另一種方法,如下所示:
if($this->get('security.context')->isGranted('ROLE_ADMIN') && $this->get('security.context')->isGranted('IS_AUTHENTICATED_ANONYMOUSLY') ){
return new RedirectResponse($this->generateUrl('adminpage'));
}
if($this->get('security.context')->isGranted('ROLE_ACCOUNTING') && $this->get('security.context')->isGranted('IS_AUTHENTICATED_ANONYMOUSLY') ){
return new RedirectResponse($this->generateUrl('accountingpage'));
}
但是,即使我使用ROLE_ACCOUNTING登錄了用戶,它也會始終評估為ROLE_ADMIN,從而為我提供“訪問被拒絕”消息。
我怎樣才能解決這個問題?
非常感謝你!
PS。 我用的是Symfony 2.7
您可以嘗試以下方法:
$user= $this->get('security.context')->getToken()->getUser();
$userId = $user->getId();
要么
$user = $this->getUser();
$userId = $user->getId();
或者,使用FOSUserBundle
$userManager = $this->container->get('fos_user.user_manager');
$user = $userManager->findUserByUsername($this->container
->get('security.context')->getToken()->getUser());
$userId = $user->getId();
然后進行角色檢查。
您得到錯誤而不是對象的原因是因為基本User類具有__toString()
方法,該方法在其中返回用戶名。
有關類似問題,請參閱此答案https://stackoverflow.com/a/12663880/5043552 。
另外,不建議您使用->hasRole()
進行第一次檢查,請參見下面的FOSUserBundle
用戶模型FOSUserBundle
/**
* Never use this to check if this user has access to anything!
*
* Use the SecurityContext, or an implementation of AccessDecisionManager
* instead, e.g.
*
* $securityContext->isGranted('ROLE_USER');
*
*/
public function hasRole($role)
您的第二個角色檢查應該可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.