手动Symfony2安全日志用户

时间:2013-06-27 11:01:00

标签: security symfony logging fosuserbundle

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

感谢您的帮助

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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();
}