1

我想在 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]

谢谢你的帮助

4

2 回答 2

1

看起来和我的很相似。也许您不应该写入会话。或者令牌需要(散列)密码。试试看,这是一个有效的代码;)

public function demologinAction(Request $request)
{
    $dm = $this->get('doctrine.odm.mongodb.document_manager');
    $repo = $dm->getRepository('AcmeUserBundle:User');
    $user = $repo->findOneByUsername('demo');

    if (!$user) {
        throw $this->createNotFoundException('No demouser found!');
    }

    $token = new UsernamePasswordToken($user, $user->getPassword(), 'main', $user->getRoles());

    $context = $this->get('security.context');
    $context->setToken($token);

    $router = $this->get('router');
    $url = $router->generate('dashboard_show');

    return $this->redirect($url);
}
于 2013-06-27T13:02:06.717 回答
0

您为什么要尝试手动登录用户?

我可能是错的,但如果原因是您可以运行一些 postLogin 代码,使用内置登录功能会更容易,但在登录操作上设置一个侦听器作为服务。然后在其中添加您的登录代码。

服务定义为:

user.login:
    class: You\Bundle\EventListener\EventListener
    arguments: [@doctrine.orm.entity_manager, @service_container]
    tags:
          - { name: kernel.event_listener, event: security.interactive_login, method: onLogin }

您的事件侦听器可能是:

public function onLogin(InteractiveLoginEvent $event)
{
    $user = $event->getAuthenticationToken()->getUser();
    $user->setLastLoggedInAt(new \DateTime());
    $user->setLoginCount($user->getLoginCount() + 1);

    $this->manager->flush();
}
于 2013-06-27T16:10:58.143 回答