Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 62 ยท Security

Login Forms and Authenticators

Add logins to Symfony: form_login, json_login, custom authenticators with passports, remember me, login throttling and access tokens, with a runnable flow.

A firewall can identify nobody until you give it an authenticator. An authenticator is a small piece of code that looks at a request and decides: "this request carries credentials, here is the user they belong to", or "these credentials are wrong", or "this is not my kind of request". Symfony ships authenticators for the common cases (HTML login forms, JSON logins, API tokens), and you can write your own for anything else.

In this lesson you will configure form_login and json_login, read the anatomy of a custom authenticator, then add remember me, login throttling and access tokens. Symfony cannot run on this site, so the real code is read-only. Two runnable plain-PHP stand-ins reproduce the authenticator flow and the throttling idea. If you have not seen the firewall, provider and hasher yet, read Security: Users and Firewalls first.

How authentication flows through a firewall

On each request, the firewall asks its authenticators in turn. The first one whose supports() method answers yes gets to run. It builds a passport (the user to look up and the proof they presented), Symfony checks the proof, and the authenticator then reacts to success or failure.

flowchart TD
    R["Request reaches a firewall"] --> S{"authenticator.supports()?"}
    S -->|"no"| N["Try the next authenticator<br/>(or continue anonymously)"]
    S -->|"yes"| A["authenticate() builds a Passport<br/>(UserBadge + credentials)"]
    A --> V{"User found and<br/>credentials valid?"}
    V -->|"yes"| OK["onAuthenticationSuccess()<br/>token stored (session)"]
    V -->|"no"| KO["onAuthenticationFailure()<br/>error response or redirect"]

Each authenticator decides whether a request is its own, proves who the user is through a passport, and then handles success or failure.

form_login

The quickest way to get a login page is the built-in form_login authenticator. Configure it on your firewall:

YAML
# config/packages/security.yaml
security:
    firewalls:
        main:
            lazy: true
            provider: app_user_provider
            form_login:
                login_path: app_login
                check_path: app_login
                enable_csrf: true
            logout:
                path: app_logout

You write two things yourself: a controller that shows the form and its errors, and a Twig template.

PHP
<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends AbstractController
{
    #[Route('/login', name: 'app_login')]
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        return $this->render('security/login.html.twig', [
            'last_username' => $authenticationUtils->getLastUsername(),
            'error' => $authenticationUtils->getLastAuthenticationError(),
        ]);
    }

    #[Route('/logout', name: 'app_logout')]
    public function logout(): never
    {
        throw new \LogicException('Intercepted by the logout key of the firewall.');
    }
}
TWIG
{% if error %}
    <p class="error">{{ error.messageKey|trans(error.messageData, 'security') }}</p>
{% endif %}

<form action="{{ path('app_login') }}" method="post">
    <input type="text" name="_username" value="{{ last_username }}" required autofocus>
    <input type="password" name="_password" required>
    <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
    <label><input type="checkbox" name="_remember_me"> Keep me logged in</label>
    <button type="submit">Log in</button>
</form>

The form posts to the same URL (check_path). The authenticator reads the fields _username, _password and _csrf_token, and these names are the defaults. The same route handles both showing the form (GET) and checking it (POST): on a POST the firewall intercepts the request before your controller runs. The logout controller body is never executed: the logout key catches the URL. The CSRF token protects the login form against forged cross-site submissions. make:auth can generate this controller and template for you.

json_login

For single-page apps and mobile clients that send JSON instead of an HTML form, use json_login:

YAML
security:
    firewalls:
        main:
            json_login:
                check_path: api_login
                username_path: email
                password_path: password
PHP
#[Route('/api/login', name: 'api_login', methods: ['POST'])]
public function apiLogin(#[CurrentUser] ?User $user): JsonResponse
{
    if ($user === null) {
        return $this->json(['message' => 'missing credentials'], 401);
    }

    return $this->json(['user' => $user->getUserIdentifier()]);
}

The client posts {"email": "...", "password": "..."}. On success the firewall authenticates the session and your controller is called, and on failure it answers with a 401 and a JSON error without calling the controller. The route needs to exist in your routing so that the path matches.

A custom authenticator

When none of the built-in ones fit (a login with a one-time code, a header from a trusted proxy), extend AbstractAuthenticator:

PHP
<?php

namespace App\Security;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;

class ApiLoginAuthenticator extends AbstractAuthenticator
{
    public function supports(Request $request): ?bool
    {
        return $request->getPathInfo() === '/api/login' && $request->isMethod('POST');
    }

    public function authenticate(Request $request): Passport
    {
        $data = $request->toArray();

        return new Passport(
            new UserBadge($data['email'] ?? ''),
            new PasswordCredentials($data['password'] ?? ''),
        );
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        return null;   // continue to the controller
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
    {
        return new JsonResponse(['error' => 'Invalid credentials.'], Response::HTTP_UNAUTHORIZED);
    }
}

You enable it on the firewall with custom_authenticators: [App\Security\ApiLoginAuthenticator]. Look at what the passport holds. The UserBadge says which user (Symfony asks the user provider to load it). The credentials say what proof was given. Symfony checks them for you: PasswordCredentials is verified against the stored hash with the configured hasher. You can attach more badges, such as CsrfTokenBadge and RememberMeBadge. If the credentials are a token that needs no password check, use SelfValidatingPassport instead. Returning null from the success method lets the request continue, while returning a Response replaces it (a redirect to the dashboard, for example).

The first stand-in builds the same flow in plain PHP: a mini firewall asks authenticators in order, passports carry a user identifier and a proof, and success or failure is reported. It has a password-style authenticator and a bearer-token one.

PHP The authenticator flow (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the two failure lines for a wrong password and an unknown user: they print the same message. A login must never reveal which of the two was wrong, otherwise attackers can find out which emails have accounts. Symfony hides this too and shows a generic "Invalid credentials." message.

Remember me

A session cookie ends when the browser session ends. The remember me feature adds a long-lived cookie that logs the user in again later:

YAML
security:
    firewalls:
        main:
            remember_me:
                secret: '%kernel.secret%'
                lifetime: 604800        # one week, in seconds
                signature_properties: ['password']

With form_login, the checkbox named _remember_me turns it on (as in the template above). The cookie holds the user identifier, an expiry time and a signature computed with your secret, so nobody can forge it. With signature_properties: ['password'], changing the user's password invalidates every remember-me cookie of that user. In a custom authenticator, you add a RememberMeBadge to the passport and call ->enable(), or use the always-on option.

Login throttling

Without a limit, an attacker can try millions of passwords. The login_throttling option counts failed attempts and answers with "too many failed login attempts" once a limit is reached:

YAML
security:
    firewalls:
        main:
            login_throttling:
                max_attempts: 5
                interval: '15 minutes'

It needs the rate limiter component (composer require symfony/rate-limiter) and counts attempts both per IP address and per username combined with the IP, so one user cannot lock out another. It works with form_login, json_login and custom authenticators that use the passport system.

The second stand-in shows the idea behind both throttling and remember me: a counter per key with a limit, and a signed token that cannot be forged. It uses a fixed clock so that the output never changes.

PHP Throttling and signed cookies (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Access tokens for APIs

Mobile apps and API clients usually send a token in a header instead of logging in with a password: Authorization: Bearer <token>. Symfony has the access_token authenticator for this. You write one small class that turns a token string into a user:

YAML
security:
    firewalls:
        api:
            pattern: ^/api
            stateless: true
            access_token:
                token_handler: App\Security\AccessTokenHandler
PHP
<?php

namespace App\Security;

use App\Repository\AccessTokenRepository;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

class AccessTokenHandler implements AccessTokenHandlerInterface
{
    public function __construct(private AccessTokenRepository $tokens) {}

    public function getUserBadgeFrom(#[\SensitiveParameter] string $accessToken): UserBadge
    {
        $token = $this->tokens->findOneByValue($accessToken);

        if ($token === null || !$token->isValid()) {
            throw new BadCredentialsException('Invalid credentials.');
        }

        return new UserBadge($token->getUserIdentifier());
    }
}

The stateless: true setting tells Symfony not to use a session for this firewall: every request must carry its own token, which is what API clients expect and which scales well. Store only a hash of long-lived tokens in your database, and give them an expiry date, just as you would with passwords.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does an authenticator's supports() method decide?

    supports() lets an authenticator skip requests that are not its own, so several authenticators can share one firewall.
  2. 2. What does the UserBadge in a passport contain?

    The UserBadge names which user is trying to log in. The credentials in the passport prove it.
  3. 3. Why should a login form show the same error for a wrong password and an unknown email?

    Different messages would reveal whether an account exists (user enumeration).
  4. 4. Why use stateless: true on an API firewall with access tokens?

    A stateless firewall stores nothing between requests, which suits token-based APIs.
  5. 5. What does signature_properties: ['password'] do for remember me?

    The listed properties are part of the cookie signature. When one changes, old cookies no longer verify.

Summary

  • An authenticator checks supports(), builds a passport in authenticate() and handles success or failure; the first supporting authenticator runs.
  • form_login and json_login cover HTML and JSON logins; AbstractAuthenticator covers everything else.
  • A passport pairs a UserBadge (who) with credentials (proof); SelfValidatingPassport skips the password check.
  • remember_me uses a signed long-lived cookie, and login_throttling limits failed attempts.
  • access_token with stateless: true authenticates API clients from a bearer token via your handler class.

Next up: Authorization: Roles and Voters.