FOSUserBundle access_control

时间:2015-08-17 21:25:15

标签: php symfony

当我登录时,我可以访问loginAction并且我可以再次登录 我希望有一个人可以帮助我。 这是我的security.yml和SecuirtyController。

security.yml

security:
encoders:
    FOS\UserBundle\Model\UserInterface: bcrypt

providers:
    fos_userbundle:
        id: fos_user.user_provider.username

firewalls:
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_provider: security.csrf.token_manager # Use form.csrf_provider instead for Symfony <2.4

        logout:       true
        anonymous:    true

access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN }

role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: ROLE_ADMIN

SecurityController

class SecurityController extends \FOS\UserBundle\Controller\SecurityController
{
    protected function renderLogin(array $data){
        #return new RedirectResponse('/');
        $securityContext = $this->get('security.authorization_checker');
        $router = $this->get('router');

        if ($securityContext->isGranted('ROLE_USER')) {
            return new RedirectResponse($router->generate('user_home'), 307);
        }

        return $this->render('FOSUserBundle:Security:login.html.twig', $data);
    }
}

1 个答案:

答案 0 :(得分:1)

你只需要像这样覆盖SecurityController:

<?php

namespace AppBundle\Controller;

use FOS\UserBundle\Controller\SecurityController as BaseController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use AppBundle\Entity\User;

class SecurityController extends BaseController
{
    public function loginAction()
    {
        if ($this->container->get('security.context')->getToken()->getUser() instanceof User){
           return new RedirectResponse($this->container->get('router')->generate('name_of_route_to_redirect'));
        }
        return parent::loginAction();
    }
}

请勿忘记查看how to overwrite FOSUser Controller