我想在 Symfony2 中手动登录用户。(我使用 fosuserbundle)。身份验证将在自定义路由中触发,例如 /login/auto
这是我与 /login/auto 匹配的控制器代码
public function loginAction(){
$em = $this->container->get('doctrine')->getManager();
$users = $em->getRepository('MybundleMainBundle:User');
$user = $users->findOneByEmail("user@user.com");
$securityContext = $this->get('security.context');
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$securityContext->setToken($token);
$this->get('session')->set('_security_'.'main', serialize($token));
return new RedirectResponse($this->generateUrl('home'));
}
但是在重定向之后,我被自动重定向到 /login 而不是 /home 所以身份验证失败
这是我的安全文件配置:
security:
providers:
fos_userbundle:
id: fos_user.user_provider.username
encoders:
FOS\UserBundle\Model\UserInterface: sha512
firewalls:
main:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
always_use_default_target_path: true
logout: true
anonymous: true
switch_user: true
remember_me:
key: %secret%
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
access_control:
- { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, role: ROLE_USER }
role_hierarchy:
ROLE_USER: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
谢谢你的帮助