0
我想在symfony中使用自動登錄功能,如觸發登錄事件和設置用戶對象。用戶對象是在控制器可用,但是當我嘗試使用其他控制器的用戶對象說annon而不是顯示登錄的用戶信息用戶對象不可訪問在symfony中的控制器
控制器A
private function autoLogin($request, $username)
{
$em = $this->getDoctrine()->getManager();
if (!$usr = $em->getRepository('AppBundle:User')->findOneBy(['username' => $username])) {
throw $this->createNotFoundException('User does not exist');
}
$token = new UsernamePasswordToken($usr, $usr->getPassword(), "secured_area", $usr->getRoles());
$this->get('security.token_storage')->setToken($token);
$loginEvent = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $loginEvent);
$user = $this->get('security.token_storage')->getToken()->getUser();
dump($user); // can see user object without any issue
if (!$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
throw new AccessDeniedException();
}
return $usr;
}
控制器B
public function editAction(Request $request)
{
$user = $this->get('security.token_storage')->getToken()->getUser();
print_r($user); // result is annon.
}
security.yml
security:
encoders:
AppBundle\Entity\User:
algorithm: bcrypt
providers:
doctrine_provider:
entity:
class: AppBundle:User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
secured_area:
anonymous: ~
provider: doctrine_provider
pattern: ^/
form_login:
login_path: security_login
check_path: security_login
csrf_token_generator: security.csrf.token_manager
logout:
path: /logout
target: /login
access_control:
- { path: ^/.*, roles: IS_AUTHENTICATED_ANONYMOUSLY }
我不知道你明白你想要做什麼。您是否在控制器中登錄用戶,然後在下一頁上用戶似乎未登錄?或者您是否將您的請求從一個控制器轉發給另一個? – Stepashka
如果您也可以提供security.yml文件,這也會很不錯。 – Stepashka
@Stepashka。我用security.yml文件內容編輯了我的問題。我試圖登錄一個控制器,然後在下一頁用戶似乎沒有登錄。該對象顯示annon。 – user1965773