I have problem with firewalls in symfony 3. From 3 days I've been struggling with this. I've read documentation and did everything according to it, but application doesn't work as I expect.
Goal: All pages (except login page) require logged in user. If user isn't logged in he should be redirect to /login page. That's all.
According to this pages:
- http://symfony.com/doc/current/book/security.html
- http://symfony.com/doc/current/cookbook/security/form_login_setup.html
I have created controller with login action and form. login_path and check_path use the same action (according to documentation). Probably something in security.yml is wrong because it doesn't work properly. My settings:
security:
providers:
in_memory:
memory:
users:
aaa:
password: aaa
roles: 'ROLE_ADMIN'
encoders:
Symfony\Component\Security\Core\User\User: plaintext
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login_firewall:
pattern: ^/login
anonymous: ~
# form_login:
# login_path: /login
# check_path: /login
secured_area:
pattern: ^/
form_login:
login_path: /login
check_path: /login
default_target_path: homepage
logout:
path: /logout
target: /login
# access_control:
# - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
# - { path: ^/, roles: IS_AUTHENTICATED_FULLY }
My login action:
<?php
/**
* @Route("/login", name="login")
*/
public function loginAction(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render(
'security/login.html.twig',
array(
// last username entered by the user
'last_username' => $lastUsername,
'error' => $error,
)
);
}
?>
Problems:
- With this configuration I'm not able to log in. Request use login action but system doesn't want to authenticate me.
- If I uncomment form_login in login_firewall firewall, Authentication works properly (I'm logged in), but I can't access homepage (system redirect me to login page although I have been authenticated.
- I've tried use access_control, but behavior was the same as in 2 point.
Please help me with that. I'm sure this is something simple but I'm new in Symfony and I don't see it.
UPDATE
Thanks to Tobias Xy I corrected security.yml. Working version:
security:
providers:
in_memory:
memory:
users:
smt:
password: smt
roles: 'ROLE_ADMIN'
encoders:
Symfony\Component\Security\Core\User\User: plaintext
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: ~
form_login:
login_path: /login
check_path: /login
default_target_path: /
logout:
path: /logout
target: /login
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: IS_AUTHENTICATED_FULLY }