Using the form_login Authentication Provider

Using the form_login Authentication Provider

Caution

To have complete control over your login form, we recommend building a form login authentication with Guard.

Symfony comes with a built-in form_login system that handles a login form POST automatically. Before you start, make sure you’ve followed the Security Guide to create your User class.

form_login Setup

First, enable form_login under your firewall:

  • YAML

    1. # config/packages/security.yaml
    2. security:
    3. # ...
    4. firewalls:
    5. main:
    6. anonymous: lazy
    7. form_login:
    8. login_path: login
    9. check_path: login
  • XML

    1. <!-- config/packages/security.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <srv:container xmlns="http://symfony.com/schema/dic/security"
    4. xmlns:srv="http://symfony.com/schema/dic/services"
    5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <config>
    9. <firewall name="main">
    10. <anonymous lazy="true"/>
    11. <form-login login-path="login" check-path="login"/>
    12. </firewall>
    13. </config>
    14. </srv:container>
  • PHP

    1. // config/packages/security.php
    2. $container->loadFromExtension('security', [
    3. 'firewalls' => [
    4. 'main' => [
    5. 'anonymous' => 'lazy',
    6. 'form_login' => [
    7. 'login_path' => 'login',
    8. 'check_path' => 'login',
    9. ],
    10. ],
    11. ],
    12. ]);

Tip

The login_path and check_path can also be route names (but cannot have mandatory wildcards - e.g. /login/{foo} where foo has no default value).

Now, when the security system initiates the authentication process, it will redirect the user to the login form /login. Implementing this login form is your job. First, create a new SecurityController:

  1. // src/Controller/SecurityController.php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. class SecurityController extends AbstractController
  5. {
  6. }

Next, configure the route that you earlier used under your form_login configuration (login):

  • Annotations

    1. // src/Controller/SecurityController.php
    2. namespace App\Controller;
    3. // ...
    4. use Symfony\Component\Routing\Annotation\Route;
    5. class SecurityController extends AbstractController
    6. {
    7. /**
    8. * @Route("/login", name="login", methods={"GET", "POST"})
    9. */
    10. public function login(): Response
    11. {
    12. }
    13. }
  • YAML

    1. # config/routes.yaml
    2. login:
    3. path: /login
    4. controller: App\Controller\SecurityController::login
    5. methods: GET|POST
  • XML

    1. <!-- config/routes.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <routes xmlns="http://symfony.com/schema/routing"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/routing
    6. https://symfony.com/schema/routing/routing-1.0.xsd">
    7. <route id="login" path="/login" controller="App\Controller\SecurityController::login" methods="GET|POST"/>
    8. </routes>
  • PHP

    1. // config/routes.php
    2. use App\Controller\SecurityController;
    3. use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
    4. return function (RoutingConfigurator $routes) {
    5. $routes->add('login', '/login')
    6. ->controller([SecurityController::class, 'login'])
    7. ->methods(['GET', 'POST'])
    8. ;
    9. };

Great! Next, add the logic to login() that displays the login form:

  1. // src/Controller/SecurityController.php
  2. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  3. public function login(AuthenticationUtils $authenticationUtils): Response
  4. {
  5. // get the login error if there is one
  6. $error = $authenticationUtils->getLastAuthenticationError();
  7. // last username entered by the user
  8. $lastUsername = $authenticationUtils->getLastUsername();
  9. return $this->render('security/login.html.twig', [
  10. 'last_username' => $lastUsername,
  11. 'error' => $error,
  12. ]);
  13. }

Note

If you get an error that the $authenticationUtils argument is missing, it’s probably because the controllers of your application are not defined as services and tagged with the controller.service_arguments tag, as done in the default services.yaml configuration.

Don’t let this controller confuse you. As you’ll see in a moment, when the user submits the form, the security system automatically handles the form submission for you. If the user submits an invalid username or password, this controller reads the form submission error from the security system, so that it can be displayed back to the user.

In other words, your job is to display the login form and any login errors that may have occurred, but the security system itself takes care of checking the submitted username and password and authenticating the user.

Finally, create the template:

  1. {# templates/security/login.html.twig #}
  2. {# ... you will probably extend your base template, like base.html.twig #}
  3. {% if error %}
  4. <div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
  5. {% endif %}
  6. <form action="{{ path('login') }}" method="post">
  7. <label for="username">Username:</label>
  8. <input type="text" id="username" name="_username" value="{{ last_username }}"/>
  9. <label for="password">Password:</label>
  10. <input type="password" id="password" name="_password"/>
  11. {#
  12. If you want to control the URL the user
  13. is redirected to on success (more details below)
  14. <input type="hidden" name="_target_path" value="/account"/>
  15. #}
  16. <button type="submit">login</button>
  17. </form>

Tip

The error variable passed into the template is an instance of Symfony\Component\Security\Core\Exception\AuthenticationException. It may contain more information - or even sensitive information - about the authentication failure, so use it wisely!

The form can look like anything, but it usually follows some conventions:

  • The <form> element sends a POST request to the login route, since that’s what you configured under the form_login key in security.yaml;
  • The username field has the name _username and the password field has the name _password.

Tip

Actually, all of this can be configured under the form_login key. See form_login Authentication for more details.

Caution

This login form is currently not protected against CSRF attacks. Read CSRF Protection in Login Forms on how to protect your login form.

And that’s it! When you submit the form, the security system will automatically check the user’s credentials and either authenticate the user or send the user back to the login form where the error can be displayed.

To review the whole process:

  1. The user tries to access a resource that is protected;
  2. The firewall initiates the authentication process by redirecting the user to the login form (/login);
  3. The /login page renders login form via the route and controller created in this example;
  4. The user submits the login form to /login;
  5. The security system intercepts the request, checks the user’s submitted credentials, authenticates the user if they are correct, and sends the user back to the login form if they are not.

CSRF Protection in Login Forms

Login CSRF attacks can be prevented using the same technique of adding hidden CSRF tokens into the login forms. The Security component already provides CSRF protection, but you need to configure some options before using it.

First, configure the CSRF token provider used by the form login in your security configuration. You can set this to use the default provider available in the security component:

  • YAML

    1. # config/packages/security.yaml
    2. security:
    3. # ...
    4. firewalls:
    5. secured_area:
    6. # ...
    7. form_login:
    8. # ...
    9. csrf_token_generator: security.csrf.token_manager
  • XML

    1. <!-- config/packages/security.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <srv:container xmlns="http://symfony.com/schema/dic/security"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:srv="http://symfony.com/schema/dic/services"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <config>
    9. <!-- ... -->
    10. <firewall name="secured_area">
    11. <!-- ... -->
    12. <form-login csrf-token-generator="security.csrf.token_manager"/>
    13. </firewall>
    14. </config>
    15. </srv:container>
  • PHP

    1. // config/packages/security.php
    2. $container->loadFromExtension('security', [
    3. // ...
    4. 'firewalls' => [
    5. 'secured_area' => [
    6. // ...
    7. 'form_login' => [
    8. // ...
    9. 'csrf_token_generator' => 'security.csrf.token_manager',
    10. ],
    11. ],
    12. ],
    13. ]);

Then, use the csrf_token() function in the Twig template to generate a CSRF token and store it as a hidden field of the form. By default, the HTML field must be called _csrf_token and the string used to generate the value must be authenticate:

  1. {# templates/security/login.html.twig #}
  2. {# ... #}
  3. <form action="{{ path('login') }}" method="post">
  4. {# ... the login fields #}
  5. <input type="hidden" name="_csrf_token"
  6. value="{{ csrf_token('authenticate') }}"
  7. >
  8. <button type="submit">login</button>
  9. </form>

After this, you have protected your login form against CSRF attacks.

Tip

You can change the name of the field by setting csrf_parameter and change the token ID by setting csrf_token_id in your configuration:

  • YAML

    1. # config/packages/security.yaml
    2. security:
    3. # ...
    4. firewalls:
    5. secured_area:
    6. # ...
    7. form_login:
    8. # ...
    9. csrf_parameter: _csrf_security_token
    10. csrf_token_id: a_private_string
  • XML

    1. <!-- config/packages/security.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <srv:container xmlns="http://symfony.com/schema/dic/security"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:srv="http://symfony.com/schema/dic/services"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <config>
    9. <!-- ... -->
    10. <firewall name="secured_area">
    11. <!-- ... -->
    12. <form-login csrf-parameter="_csrf_security_token"
    13. csrf-token-id="a_private_string"
    14. />
    15. </firewall>
    16. </config>
    17. </srv:container>
  • PHP

    1. // config/packages/security.php
    2. $container->loadFromExtension('security', [
    3. // ...
    4. 'firewalls' => [
    5. 'secured_area' => [
    6. // ...
    7. 'form_login' => [
    8. // ...
    9. 'csrf_parameter' => '_csrf_security_token',
    10. 'csrf_token_id' => 'a_private_string',
    11. ],
    12. ],
    13. ],
    14. ]);

Redirecting after Success

By default, the form will redirect to the URL the user requested (i.e. the URL which triggered the login form being shown). For example, if the user requested http://www.example.com/admin/post/18/edit, then after they have successfully logged in, they will be sent back to http://www.example.com/admin/post/18/edit.

This is done by storing the requested URL in the session. If no URL is present in the session (perhaps the user went directly to the login page), then the user is redirected to / (i.e. the homepage). You can change this behavior in several ways.

Changing the default Page

Define the default_target_path option to change the page where the user is redirected to if no previous page was stored in the session. The value can be a relative/absolute URL or a Symfony route name:

  • YAML

    1. # config/packages/security.yaml
    2. security:
    3. # ...
    4. firewalls:
    5. main:
    6. form_login:
    7. # ...
    8. default_target_path: after_login_route_name
  • XML

    1. <!-- config/packages/security.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <srv:container xmlns="http://symfony.com/schema/dic/security"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:srv="http://symfony.com/schema/dic/services"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <config>
    9. <!-- ... -->
    10. <firewall name="main">
    11. <form-login default-target-path="after_login_route_name"/>
    12. </firewall>
    13. </config>
    14. </srv:container>
  • PHP

    1. // config/packages/security.php
    2. $container->loadFromExtension('security', [
    3. // ...
    4. 'firewalls' => [
    5. 'main' => [
    6. // ...
    7. 'form_login' => [
    8. // ...
    9. 'default_target_path' => 'after_login_route_name',
    10. ],
    11. ],
    12. ],
    13. ]);

Always Redirect to the default Page

Define the always_use_default_target_path boolean option to ignore the previously requested URL and always redirect to the default page:

  • YAML

    1. # config/packages/security.yaml
    2. security:
    3. # ...
    4. firewalls:
    5. main:
    6. form_login:
    7. # ...
    8. always_use_default_target_path: true
  • XML

    1. <!-- config/packages/security.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <srv:container xmlns="http://symfony.com/schema/dic/security"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:srv="http://symfony.com/schema/dic/services"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <config>
    9. <!-- ... -->
    10. <firewall name="main">
    11. <!-- ... -->
    12. <form-login always-use-default-target-path="true"/>
    13. </firewall>
    14. </config>
    15. </srv:container>
  • PHP

    1. // config/packages/security.php
    2. $container->loadFromExtension('security', [
    3. // ...
    4. 'firewalls' => [
    5. 'main' => [
    6. // ...
    7. 'form_login' => [
    8. // ...
    9. 'always_use_default_target_path' => true,
    10. ],
    11. ],
    12. ],
    13. ]);

Control the Redirect Using Request Parameters

The URL to redirect after the login can be defined using the _target_path parameter of GET and POST requests. Its value must be a relative or absolute URL, not a Symfony route name.

Defining the redirect URL via GET using a query string parameter:

  1. http://example.com/some/path?_target_path=/dashboard

Defining the redirect URL via POST using a hidden form field:

  1. {# templates/security/login.html.twig #}
  2. <form action="{{ path('login') }}" method="post">
  3. {# ... #}
  4. <input type="hidden" name="_target_path" value="{{ path('account') }}"/>
  5. <input type="submit" name="login"/>
  6. </form>

Using the Referring URL

In case no previous URL was stored in the session and no _target_path parameter is included in the request, you may use the value of the HTTP_REFERER header instead, as this will often be the same. Define the use_referer boolean option to enable this behavior:

  • YAML

    1. # config/packages/security.yaml
    2. security:
    3. # ...
    4. firewalls:
    5. main:
    6. # ...
    7. form_login:
    8. # ...
    9. use_referer: true
  • XML

    1. <!-- config/packages/security.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <srv:container xmlns="http://symfony.com/schema/dic/security"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:srv="http://symfony.com/schema/dic/services"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <config>
    9. <!-- ... -->
    10. <firewall name="main">
    11. <!-- ... -->
    12. <form-login use-referer="true"/>
    13. </firewall>
    14. </config>
    15. </srv:container>
  • PHP

    1. // config/packages/security.php
    2. $container->loadFromExtension('security', [
    3. // ...
    4. 'firewalls' => [
    5. 'main' => [
    6. // ...
    7. 'form_login' => [
    8. // ...
    9. 'use_referer' => true,
    10. ],
    11. ],
    12. ],
    13. ]);

Note

The referrer URL is only used when it is different from the URL generated by the login_path route to avoid a redirection loop.

Redirecting after Failure

After a failed login (e.g. an invalid username or password was submitted), the user is redirected back to the login form itself. Use the failure_path option to define a new target via a relative/absolute URL or a Symfony route name:

  • YAML

    1. # config/packages/security.yaml
    2. security:
    3. # ...
    4. firewalls:
    5. main:
    6. # ...
    7. form_login:
    8. # ...
    9. failure_path: login_failure_route_name
  • XML

    1. <!-- config/packages/security.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <srv:container xmlns="http://symfony.com/schema/dic/security"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:srv="http://symfony.com/schema/dic/services"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <config>
    9. <!-- ... -->
    10. <firewall name="main">
    11. <!-- ... -->
    12. <form-login failure-path="login_failure_route_name"/>
    13. </firewall>
    14. </config>
    15. </srv:container>
  • PHP

    1. // config/packages/security.php
    2. $container->loadFromExtension('security', [
    3. // ...
    4. 'firewalls' => [
    5. 'main' => [
    6. // ...
    7. 'form_login' => [
    8. // ...
    9. 'failure_path' => 'login_failure_route_name',
    10. ],
    11. ],
    12. ],
    13. ]);

This option can also be set via the _failure_path request parameter:

  1. http://example.com/some/path?_failure_path=/forgot-password
  1. {# templates/security/login.html.twig #}
  2. <form action="{{ path('login') }}" method="post">
  3. {# ... #}
  4. <input type="hidden" name="_failure_path" value="{{ path('forgot_password') }}"/>
  5. <input type="submit" name="login"/>
  6. </form>

Customizing the Target and Failure Request Parameters

The name of the request attributes used to define the success and failure login redirects can be customized using the target_path_parameter and failure_path_parameter options of the firewall that defines the login form.

  • YAML

    1. # config/packages/security.yaml
    2. security:
    3. # ...
    4. firewalls:
    5. main:
    6. # ...
    7. form_login:
    8. target_path_parameter: go_to
    9. failure_path_parameter: back_to
  • XML

    1. <!-- config/packages/security.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <srv:container xmlns="http://symfony.com/schema/dic/security"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:srv="http://symfony.com/schema/dic/services"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <config>
    9. <!-- ... -->
    10. <firewall name="main">
    11. <!-- ... -->
    12. <form-login target-path-parameter="go_to"/>
    13. <form-login failure-path-parameter="back_to"/>
    14. </firewall>
    15. </config>
    16. </srv:container>
  • PHP

    1. // config/packages/security.php
    2. $container->loadFromExtension('security', [
    3. // ...
    4. 'firewalls' => [
    5. 'main' => [
    6. // ...
    7. 'form_login' => [
    8. 'target_path_parameter' => 'go_to',
    9. 'failure_path_parameter' => 'back_to',
    10. ],
    11. ],
    12. ],
    13. ]);

Using the above configuration, the query string parameters and hidden form fields are now fully customized:

  1. http://example.com/some/path?go_to=/dashboard&back_to=/forgot-password
  1. {# templates/security/login.html.twig #}
  2. <form action="{{ path('login') }}" method="post">
  3. {# ... #}
  4. <input type="hidden" name="go_to" value="{{ path('dashboard') }}"/>
  5. <input type="hidden" name="back_to" value="{{ path('forgot_password') }}"/>
  6. <input type="submit" name="login"/>
  7. </form>

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.