Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 62 ยท Security

Security: Users and Firewalls

Understand Symfony security: the user class, user providers, firewalls, password hashing, make:user and access_control, with runnable PHP stand-ins.

Almost every real application has to answer two questions about each request. Who are you? (authentication) and are you allowed to do this? (authorization). Symfony's Security component answers both, and it is built from a few small parts that fit together: a user class, a user provider that loads users, a firewall that guards a part of the site, password hashers, and access control rules.

This lesson is the map. You will meet each part, read a complete security.yaml, and see how a request travels through it. The next lessons cover login forms and authenticators and roles and voters in depth. The real Symfony configuration here is read-only because the framework cannot run on this site. Two plain-PHP stand-ins let you try the key ideas: password hashing and rule matching.

Install and generate a user

Terminal
composer require symfony/security-bundle
php bin/console make:user

The make:user command asks a few questions (class name, the field that identifies a user such as email, whether to store hashed passwords) and then creates a User entity, its repository and the first version of config/packages/security.yaml. You then run make:migration and doctrine:migrations:migrate to create the table.

The user class

A user is any class that implements Symfony\Component\Security\Core\User\UserInterface. If users have passwords, it also implements PasswordAuthenticatedUserInterface. The generated class looks like this (shortened):

PHP
<?php

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;

#[ORM\Entity(repositoryClass: UserRepository::class)]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 180, unique: true)]
    private ?string $email = null;

    /** @var list<string> */
    #[ORM\Column]
    private array $roles = [];

    #[ORM\Column]
    private ?string $password = null;

    public function getUserIdentifier(): string
    {
        return (string) $this->email;
    }

    public function getRoles(): array
    {
        $roles = $this->roles;
        $roles[] = 'ROLE_USER';          // every user has at least this role

        return array_unique($roles);
    }

    public function getPassword(): ?string
    {
        return $this->password;           // the HASH, never the plain password
    }
}

The key methods are small. getUserIdentifier() returns the unique value that identifies the user (the email, here). getRoles() returns strings such as ROLE_ADMIN, and by convention each starts with ROLE_. getPassword() returns the hash. Older versions of the interface also had an eraseCredentials() method for clearing temporary data, which you may still see in generated code.

Your user does not have to be a Doctrine entity. It can come from an API, a file or an LDAP server, as long as a user provider can produce objects of that class.

User providers

A user provider has two jobs. It loads a user from the identifier found in the request (the email typed into a login form), and it reloads the user from its identifier at the start of each later request, so the session stores only a small token and the application always sees fresh data. For an entity, Symfony ships an "entity" provider:

YAML
# config/packages/security.yaml
security:
    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email

There are also a memory provider (users written in the config, useful for tests and small tools), a chain provider that tries several providers in order, and id providers for your own service.

Password hashing

Never store passwords as plain text and never invent your own scheme. Symfony stores a hash: a one-way, deliberately slow transformation with a random salt built in. The auto setting selects the best available algorithm and can upgrade old hashes later:

YAML
security:
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'

You hash with the UserPasswordHasherInterface service, for example when registering a user, and check with isPasswordValid():

PHP
public function register(
    Request $request,
    UserPasswordHasherInterface $passwordHasher,
    EntityManagerInterface $entityManager,
): Response {
    $user = new User();
    $user->setEmail($request->request->getString('email'));
    $user->setPassword(
        $passwordHasher->hashPassword($user, $request->request->getString('password'))
    );

    $entityManager->persist($user);
    $entityManager->flush();

    // ...
}

Because the salt is random, hashing the same password twice gives different strings. That is why you can never compare hashes with ===; you ask the hasher to verify a plain password against a stored hash. The stand-in below uses PHP's own password_hash() and password_verify(), which are what the native Symfony hasher is built on. It prints only values that are the same on every run.

PHP Hashing and verifying passwords (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.

In a real Symfony app, if your repository implements PasswordUpgraderInterface, the framework re-hashes a user's password automatically at login whenever the configured algorithm has become stronger than the stored hash.

Firewalls

A firewall is the part that decides how a request is authenticated. Each request is matched against your firewalls from top to bottom, and only the first matching firewall is used. Inside it, authenticators (login form, JSON login, API token, and so on) try to identify the user.

YAML
security:
    firewalls:
        dev:
            pattern: ^/(_profiler|_wdt|assets|build)/
            security: false

        main:
            lazy: true
            provider: app_user_provider
            # authenticators are added here (see the next lesson)

The dev firewall turns security off for the profiler and static assets so that development tools work. The main firewall has no pattern, so it matches everything else. The lazy: true option means the session and user are only loaded if your code actually asks who the user is, which keeps public pages cheap and cacheable.

A firewall does not by itself say "this page needs a login". A firewall only enables authentication. Which pages are restricted is decided by access control, described next. Many beginners guess the opposite and wonder why anonymous users still see their pages.

flowchart TD
    R["Request"] --> F{"First firewall<br/>whose pattern matches"}
    F -->|"dev (security: false)"| C["Controller"]
    F -->|"main"| A["Authenticators try to identify the user"]
    A --> AC{"access_control rules<br/>(first match wins)"}
    AC -->|"allowed"| C
    AC -->|"denied, anonymous"| L["Redirect to login<br/>(entry point)"]
    AC -->|"denied, logged in"| D["403 Access Denied"]

A request is handled by one firewall, then checked against the access control rules before the controller runs.

access_control

The access_control list protects URL patterns. Rules are checked in order and the first match wins:

YAML
security:
    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }
        - { path: ^/account, roles: ROLE_USER }
        - { path: ^/login, roles: PUBLIC_ACCESS }

path is a regular expression, and roles is the role the user must have. PUBLIC_ACCESS is a special attribute that lets everyone in, including anonymous visitors. Careful with ordering: if you put ^/ first, it matches everything and your later rules never run. Rules can also match on host, methods and ip. You can protect individual controllers with the #[IsGranted] attribute as well, covered in Authorization: Roles and Voters.

To see what Symfony thinks, run php bin/console debug:firewall (lists firewalls) and php bin/console debug:firewall main (shows one firewall's settings). In controllers, $this->getUser() returns the logged-in user or null, and the #[CurrentUser] argument attribute does the same with a type hint.

The second stand-in implements the "first matching rule wins" logic in a few lines. Changing the order of two rules changes the outcome, which is the most common access control bug.

PHP First matching access rule wins (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.

A complete security.yaml

Putting it together, a small application's file looks like this:

YAML
security:
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'

    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email

    firewalls:
        dev:
            pattern: ^/(_profiler|_wdt|assets|build)/
            security: false
        main:
            lazy: true
            provider: app_user_provider

    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }
        - { path: ^/account, roles: ROLE_USER }

Without an authenticator the main firewall can identify nobody yet, so protected pages would simply deny everyone. Adding a login is the topic of Login Forms and Authenticators. Also remember that hashing in tests can be made cheaper with a when@test: block that lowers the algorithm cost, so that test suites stay fast.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can you not compare two password hashes with === to check a login?

    A salted hash differs on every call. Use password_verify() or the hasher's isPasswordValid() to check a password against the stored hash.
  2. 2. How many firewalls handle a single request?

    Firewalls are matched top to bottom and the first match is used for the whole request.
  3. 3. What does a firewall configuration by itself NOT do?

    A firewall only enables authentication. Restricting URLs is the job of access_control (or attributes like #[IsGranted]).
  4. 4. In access_control, you list { path: ^/, roles: ROLE_USER } before { path: ^/login, roles: PUBLIC_ACCESS }. What happens?

    The first matching rule wins, so the broad rule catches /login and the public rule is never reached.
  5. 5. What is a user provider used for?

    The provider loads users by identifier (for example the email) and refreshes the user from the session on each request.

Summary

  • Security splits into authentication (who are you?) and authorization (may you do this?).
  • A user class implements UserInterface (and PasswordAuthenticatedUserInterface); make:user generates it with a provider and a first security.yaml.
  • Passwords are stored as salted hashes; use the hasher service to hash and verify, never ===.
  • Only the first matching firewall handles a request, and a firewall enables authentication but does not restrict URLs.
  • access_control rules protect paths, the first match wins, and PUBLIC_ACCESS lets everyone in.

Next up: Login Forms and Authenticators.