0

So, I'm using FOSUserBundle and symfony 2.8 project

if there is any way to redirect anonymous user to /login page, if he required / page?

Majesty
  • 2,097
  • 5
  • 24
  • 55

2 Answers2

1

Use a firewall to protect /:

# app/config/security.yml

security:

    firewalls:
        app:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
            logout:       true
            anonymous:    true

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

More details in the FOSUserBundle docs.

Jonny
  • 2,223
  • 23
  • 30
  • that is how my security.yml looks like now, but it isn't working for me, I don't know why – Majesty Apr 24 '16 at 13:15
  • Did you follow the FOSUserBundle guide? Activated the bundle etc – Jonny Apr 24 '16 at 15:24
  • I suspect conflicting rules within your `security.yml`. Feel free to post your full file here: https://gist.github.com – Jonny Apr 25 '16 at 09:17
0

First, check if the user is authorized. Then, use an if condition to redirect the user.

Full example of your index:

public function indexAction()
{
    $context = $this->container->get('security.authorization_checker');
    if (!($context->isGranted('IS_AUTHENTICATED_REMEMBERED'))) {
        $this->redirect('http://yourpage.com/login');
    } else {
      //Do your other stuff here
    }
}
Community
  • 1
  • 1
manniL
  • 7,157
  • 7
  • 46
  • 72