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')); 
}

しかし、リダイレクト後、/home ではなく /login に自動的にリダイレクトされるため、認証に失敗しました。

ここに私のセキュリティファイルの設定があります:

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

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 に答える