Stateless firewall in Symfony: authenticating an API with an access token

A stateless firewall in Symfony authenticates every API request with an access token, without session or cookie: the token comes with every call.

final class SceauHandler implements AccessTokenHandlerInterface
{
    public function __construct(private readonly GuildeRepository $guildeRepository)
    {
    }

    public function getUserBadgeFrom(#[\SensitiveParameter] string $accessToken): UserBadge
    {
        $guilde = $this->guildeRepository->findOneBy(['sceau' => $accessToken])
            ?? throw new BadCredentialsException('No guild bears this seal.');

        return new UserBadge($guilde->getUserIdentifier(), static fn () => $guilde);
    }
}
// security.yaml: api: { pattern: ^/api, stateless: true, access_token: { token_handler: App\Security\SceauHandler } }

An API client doesn't keep a session cookie. With stateless: true and access_token, Symfony reads the Authorization: Bearer … header and hands it to the handler, which returns a UserBadge or rejects the token: the response is then a 401. No session is opened, and the session of an employee logged in to the website grants no rights over the API. The trap: the order of the firewalls. Symfony only keeps one, the first whose pattern matches; declared after main, which has no pattern, the api firewall never sees a request go by, and the client gets a redirect to the login page.

The exercises have you give each guild a seal to book a table, find the guild that bears it and attach the booking to it, then open registration for the storytelling evenings to the guilds, rejected with a 401 without a valid seal.

2 exercises work on this concept, by writing code in the browser.

In the tracks

Related concepts

access_tokenJSON API#[MapRequestPayload]HTTP status codes