Is it possible to perform an automatic redirect to the some route (i.e. /) for the specific route /login
only for users that are AUTHENTICATED
? and How?
I'm using FOSUserBundle.
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
providers:
fos_userbundle:
id: fos_user.user_provider.username_email
firewalls:
main:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
login_path: /accedi
check_path: /login_check
default_target_path: /
oauth:
resource_owners:
facebook: "/login/check-facebook"
google: "/login/check-google"
login_path: /accedi
failure_path: /accedi
default_target_path: /
oauth_user_provider:
service: my_user_provider
logout:
path: /logout
target: /
invalidate_session: false
anonymous: ~
login:
pattern: ^/login$
security: false
remember_me:
key: "%secret%"
lifetime: 31536000 # 365 days in seconds
path: /
domain: ~
oauth_authorize:
pattern: ^/oauth/v2/auth
form_login:
provider: fos_userbundle
check_path: _security_check
login_path: _demo_login
anonymous: true
oauth_token:
pattern: ^/oauth/v2/token
security: false
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/accedi$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/registrati, role: IS_AUTHENTICATED_ANONYMOUSLY }
As you are using FOSUserBundle the rendering of the login form takes place in SecurityController::renderLogin()
.
The solution is bascially:
IS_AUTHENTICATD_ANONYMOUSLY
I assume you have already created a bundle extending FOSUserBundle which holds your User
Entity.
I assume this bundle is called YourUserBundle
and is located at src/Your/Bundle/UserBundle
.
Now copy (not cut) the SecurityController
vendor/friendsofsymfony/user-bundle/src/FOS/UserBundle/Controller/SecurityController.php
to (in order to override the one provided by FOSUserBundle)
src/Your/Bundle/UserBundle/Controller/SecurityController.php
add the use-statement for RedirectResponse
and edit the renderLogin()
method like this:
use Symfony\Component\HttpFoundation\RedirectResponse;
// ...
protected function renderLogin(array $data)
{
if (false === $this->container->get('security.context')->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
return new RedirectResponse('/', 403);
}
$template = sprintf('FOSUserBundle:Security:login.html.%s', $this->container->getParameter('fos_user.template.engine'));
return $this->container->get('templating')->renderResponse($template, $data);
}
Now instead of security.context
use security.authorization_checker
.
http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With