07 Aug 2026

Harden a Symfony Admin Login: 4 Layers, in the Right Order

Harden a Symfony Admin Login: 4 Layers, in the Right Order

Credential spraying is a quiet attack: one common password, tried against many accounts, slowly enough that no single account trips a lockout. A forged session is quieter still, because the login form never sees it. When either one points at a Symfony admin, the request I get is two words long. "Lock it down."

I've built each of these layers on Symfony apps from 4.4 up to 8, the same range I cover when upgrading legacy Symfony apps: an IP allowlist in front of the admin, emailed two-factor codes, forced password rotation with a sane session lifetime, and Cloudflare Turnstile on the login form. None of them is hard on its own. Shipped together, three of them want to edit security.yaml and each one changes what a "successful login" means for the next. Put them in the wrong order and you get a login loop that is tedious to unpick.

How do you lock down a Symfony admin after a credential-spraying attack?

Flush every live session by emptying the session store and rotating the remember-me secret. Then build three layers in order: emailed 2FA, an admin IP allowlist that runs before the firewall, then password rotation. They share security.yaml, so order matters. Cloudflare Turnstile is independent and can go in anytime. Roll out to users allowlist first.

What each layer buys you, and what it costs the people who log in:

LayerWhat it stopsWhat it costs the user
Session flush (empty the store, rotate the remember-me secret)Sessions and remember-me cookies issued before the flushOne forced logout for everyone
Emailed 2FA + rate limitsA sprayed password that happens to be correctA six-digit code from their inbox on each login
Admin IP allowlistAny request to /admin from an address nobody approved, forged cookie includedOne approval per new address (home, office, VPN)
Password rotation + session lifetimeOld passwords that leaked somewhere else and still work hereA new password every N days; fewer surprise logouts
Cloudflare TurnstileScripted login posts, before any password is checkedUsually nothing; sometimes a click

The first hour: actually flush every session

If the trigger is a stolen or forged session, the first thing to ship is a flush, and it's easy to do one that looks right and isn't.

Renaming the session cookie (off PHPSESSID) is not a flush. The old session files are still in the store, the new cookie name is visible in any response, and an attacker holding a stolen ID can simply send it under the new name. I still rename it, as fingerprint hygiene. It invalidates nothing.

What does invalidate sessions:

  • Empty the session store. Delete the session files, truncate the sessions table or clear the Redis prefix, whichever the app uses. Moving save_path to a new directory has the same effect, and Layer 3's session config does exactly that.
  • Rotate the remember-me secret. A remember-me cookie re-authenticates its holder into a brand-new session, so emptying the store misses them. Renaming the remember-me cookie is bypassable for the same reason as the session rename. Changing the secret it's signed with (by default kernel.secret, so APP_SECRET) is what kills them. Anything else signed with that secret breaks too, so check what uses it first.

Everyone logs out once. After an incident, that's the point.

Why the order matters

There are two orders here. The first is the request-time order, where each layer sits in Symfony's kernel.request chain:

PriorityListenerWhat exists at that point
512Admin IP guardThe raw request. No route, no session, no token
32Symfony's RouterListenerThe matched route name gets resolved here
16Turnstile guardRoute name known, nobody authenticated yet
8Symfony's FirewallThe authenticator runs; scheb swaps in a pending 2FA token
6Password expiration subscriberA resolved user with a real token

I confirm the real chain after every layer with bin/console debug:event-dispatcher kernel.request.

The second is the build order, and that one isn't the same as the request order:

  1. 2FA first. Both of the others reference it. The login audit log records a "2FA pending" event, and the rotation subscriber has to step aside while a code is owed. Build 2FA last and both get written blind.
  2. IP allowlist second. It sits in front of the firewall, so nothing the other layers do to security.yaml affects it. But its login log needs the 2FA token states to exist before it can classify them.
  3. Password rotation third. Its subscriber needs the finished list of routes a blocked user must still reach: login, logout, the 2FA challenge and its check path, and the allowlist's approve and decline links. That list only exists once the other two have shipped.

Turnstile has no slot in this sequence. It doesn't touch security.yaml or access_control at all, and it ships switched off, so it can go in at any point.

Build them one at a time, and keep each one separable so it can be backed out without taking the others along. Switching them on for real users follows a third order, covered near the end.

Layer 1: emailed 2FA with SchebTwoFactorBundle

After a correct password, the user gets a numeric code by email. Until they enter it they hold a TwoFactorToken, which satisfies no role, so every protected route sends them back to the challenge.

Pick the scheb major that matches the app: ^5.0 for Symfony 4.4 and 5.x, ^7.0 for 6.4 and 7.x, ^8.0 for 7.4 and 8. Install scheb/2fa-email alongside it, or 2FA is configured but never triggers.

The setting that fails silently

# config/packages/scheb_2fa.yaml
scheb_two_factor:
    security_tokens:
        # New authenticator system:
        - Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken
        - Symfony\Component\Security\Http\Authenticator\Token\PostAuthenticationToken
        # Guard firewalls (Symfony 4.4 / 5.x) use instead:
        # - Symfony\Component\Security\Guard\Token\PostAuthenticationGuardToken
    email:
        enabled: true
        mailer: App\Service\EmailService
        digits: 6
        template: 'security/2fa_form.html.twig'

security_tokens is the list of post-login token classes the bundle is allowed to interrupt. Scheb 5 defaults to all of them, so an app can work without this key; the moment you write it, you override that default. Name the wrong class and there's no error anywhere. Login just succeeds, no code is generated, and the feature looks installed.

The mailer key points at the app's own mail service (implementing AuthCodeMailerInterface), so the code arrives branded, from the address users already recognize.

Who gets challenged

public function isEmailAuthEnabled(): bool
{
    return $this->hasRole(self::ROLE_SUPER_ADMIN)
        || $this->hasRole(self::ROLE_ADMIN)
        || $this->hasRole(self::ROLE_APPROVER);
}

public function getEmailAuthCode(): string   // ?string on scheb 8.x
{
    return (string) $this->authCode;
}

List every role explicitly. The usual hasRole() ignores the role hierarchy, so a super admin does not answer true to hasRole('ROLE_ADMIN'). Then check which roles actually exist in the database: on one app I hardened, "admins and approvers" turned out to mean everyone.

The access_control lines

access_control:
    # Above the app's own rules. First match wins.
    - { path: ^/admin/2fa, role: IS_AUTHENTICATED_2FA_IN_PROGRESS }
    - { path: ^/2fa,       role: IS_AUTHENTICATED_2FA_IN_PROGRESS }

These must come before any catch-all. A ^/ rule higher up demands a role the pending token can't have, and the user bounces between the challenge and the login form forever. That's the first of the login loops, and the reason 2FA goes in before anything else touches this file.

Two things I tell the client rather than decide for them. Scheb stores the emailed code in plaintext and doesn't clear it after use, so a database dump holds a live second factor; a listener on the 2FA success event that clears the column closes that. Newer scheb majors also ship a code_reuse_cache option; scheb 5 doesn't have it. And if mail is down, nobody gets a code. The setup has no built-in bypass, so plan one before launch, such as a console command that switches 2FA off for one named account, and test it.

Rate limits underneath

Spraying uses a different username on every attempt, so a limit per username never fires. Symfony's built-in login_throttling also keeps a per-IP limiter, and that's the half that matters here:

security:
    firewalls:
        admin:
            login_throttling:
                max_attempts: 5          # example value
                interval: '15 minutes'

The 2FA check path needs its own limit. I don't rely on the bundle to throttle wrong codes, and an uncleared code makes guessing more attractive. A small kernel.request listener on POSTs to the check routes, consuming a framework.rate_limiter keyed by the user, closes it.

Layer 2: an admin IP allowlist that runs before the firewall

This is the layer that answers the forged-cookie case: the check runs before the firewall ever looks at the cookie.

The guard

public static function getSubscribedEvents(): array
{
    // Ahead of RouterListener (32) and the firewall (8) on purpose.
    return [KernelEvents::REQUEST => ['onKernelRequest', 512]];
}

public function onKernelRequest(RequestEvent $event): void
{
    if (!$this->enabled || !$event->isMainRequest()) {
        return;
    }

    $request = $event->getRequest();
    if (0 !== stripos($request->getPathInfo(), '/admin')) {
        return;
    }

    $ip = $request->getClientIp();
    if (null === $ip || '' === $ip) {
        $event->setResponse($this->deny($request, 'unidentified'));
        return;
    }

    // Break-glass: read from the environment, never the database.
    if ($this->accessList->isBootstrapAllowed($ip)) {
        return;
    }

    $status = $this->accessList->statusFor($ip);
    if (null === $status) {
        $this->registry->registerPending($ip, $request);
        $event->setResponse($this->deny($request, 'pending', $ip));
        return;
    }

    $this->registry->recordSighting($ip, $request);
    if (!$status->allowsAccess()) {
        $event->setResponse($this->deny($request, $status->value, $ip));
    }
}

Priority 512 means an unapproved address is refused before a session starts or a token is deserialized.

The break-glass list (ADMIN_IP_ALLOWLIST) comes from the environment on purpose. No database problem can lock every administrator out at once. It ships as 127.0.0.1,::1, which lets nobody in from outside, so a real address goes in before deploy. There's also an ADMIN_IP_GUARD_ENABLED kill switch: deploy with it off, seed the approved addresses from the console, then turn it on.

Trusted proxies, in both directions

Everything above depends on getClientIp() returning the real client. Behind Cloudflare or a load balancer with framework.trusted_proxies unset, it returns the proxy's address. The first approval then approves the proxy, and the proxy is the whole internet.

The opposite mistake is just as bad. Trust 0.0.0.0/0 or REMOTE_ADDR, or leave the origin reachable without going through Cloudflare, and anyone can send X-Forwarded-For and pick their own IP. With the break-glass default, a forged X-Forwarded-For: 127.0.0.1 would walk straight in. Trust only the real proxy ranges, firewall the origin so it only accepts Cloudflare's IPs, and test it by sending a forged header yourself. The same IP is what Turnstile passes to Cloudflare, so this one setting matters for both layers.

Never query the database per request

The guard runs on every admin request, so the whole table lives in a cache pool:

[
    'exact' => ['203.0.113.10' => 'approved'],
    'ranges' => [
        ['cidr' => '198.51.100.0/24', 'status' => 'declined'],
    ],
]

An exact match beats a range, and among ranges a decline beats an approval. Invalidation hangs off a Doctrine entity listener rather than the approval service, because Sonata's edit and delete forms write through the entity manager and never call your service. Get that wrong and a deleted address keeps working until the 60-second cache expires.

Approve and decline by email, safely

An unknown address is stored as pending and reviewers get approve and decline links by email. The details that matter:

  • The review routes live outside /admin. The reviewer is often sitting behind an address that isn't approved yet.
  • A GET never acts. Link scanners fetch every URL in an email, so GET shows a confirmation page and a POST with a CSRF token does the work.
  • Check framework.router.default_uri. The notifier runs before routing. Unset, the links point at http://localhost; with a trailing slash, they 404.

Person or script?

Reviewers need to know whether a new address was a colleague or a script, so the allowlist scores each request from headers already on it. Sec-Fetch-*, an HTML Accept and Accept-Language earn most of the points; a browser-shaped user agent earns only 10, because it's trivial to fake. A user agent that names an automation tool, like curl's default, loses 60. Fake a Chrome user agent and that penalty goes away, but the browser headers don't come with it, so the request still scores 10 out of 100. A real browser scores 100.

Every header is attacker-controlled, so green means "nothing gave it away", never "confirmed human". Once an address acts like a script, a one-way flag pins it red.

Search engines find admin URLs too. On one project a single exposed day produced 74 pending rows and 121 review emails, all about Bing. Self-identified crawlers now get a 404 and are declined with no email.

The login log, with geo-location

The log answers "has this already happened". One row per authentication event: success, failure, logout and the important one:

// The password was right but a code is still owed. Recording this as a
// success would make the log claim access that was never granted.
$pendingTwoFactor = $token instanceof TwoFactorTokenInterface;

$log->setEvent($pendingTwoFactor ? LoginEvent::TWO_FACTOR_PENDING : LoginEvent::SUCCESS);

This is why 2FA comes first. Scheb swaps the token before LoginSuccessEvent fires, so without this check a correct password logs as a full login.

Each row also gets a location, compared against the address on the account's profile, with a red flag when they disagree. The lookup never happens during login, or a slow geo provider becomes a slow login. The flag is for investigation only; VPNs produce honest ones.

Layer 3: password rotation and a session that outlives 24 minutes

A nullable passwordChangedAt column, a max-age parameter (90 days is the common default), and a request subscriber that redirects an expired user to a change-password page they can't leave until they pick a new password.

/** Routes a user must still reach while their password is expired. */
private const ALLOWED_ROUTES = [
    'app_change_password',
    'login', 'logout', 'app_logout',
    '2fa_login', '2fa_login_check', 'admin_2fa_login', 'admin_2fa_login_check',
    'app_forgot_password_request', 'app_reset_password', 'app_check_email',
];

public static function getSubscribedEvents(): array
{
    // After the firewall (8) has resolved the token, before the controller.
    return [KernelEvents::REQUEST => ['onKernelRequest', 6]];
}

That route list is why rotation goes last. Forget the 2FA check path and an expired user gets redirected away from the challenge they need to finish. That's the second login loop.

Inside the handler, isGranted('IS_AUTHENTICATED_REMEMBERED') keeps it from fighting 2FA: it excludes scheb's pending token, so a waiting challenge always wins over the rotation redirect, while remember-me users still have to rotate.

Don't stamp the timestamp inside setPassword(). upgradePassword() rehashes the same password on login and would silently reset everyone's clock. And null means expired: with no backfill, every account rotates on its next login.

The session half

Stock Symfony leaves session lifetime at PHP defaults: the cookie dies with the browser, and the server-side file is swept after gc_maxlifetime, which is 1,440 seconds. Twenty-four minutes.

framework:
    session:
        handler_id: session.handler.native_file
        name: APPSESSID
        cookie_secure: auto
        cookie_samesite: lax
        cookie_lifetime: 86400
        gc_maxlifetime: 86400
        save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'

Two silent traps. save_path is ignored while handler_id is null, though debug:config still prints it. And cookie_lifetime alone gives you a day-long cookie pointing at a file PHP deleted after 24 minutes; both values have to move together.

The new save_path is the store flush from the first hour, if you didn't do it separately. The name line is the hygiene rename; search the stack for a hardcoded PHPSESSID in a load balancer or nginx rule, because a rename breaks those as a silent logout loop.

One trade-off to raise: a day-long session is also a day-long window for a stolen admin cookie. For the admin side I'd suggest a shorter lifetime or an idle timeout, even if regular users keep the longer one.

Layer 4: Cloudflare Turnstile on the login form

Turnstile stops spraying from reaching the password check at all. I add it as about 200 lines of plain app code across five files, no bundle.

The guard listener runs at priority 16: after the router, so the route name is known, and before the firewall, so a scripted login post is refused before any authenticator reads a password or the login throttle counts it. Forms opt in through config:

parameters:
    app.turnstile.surfaces:
        login:
            action: login
            routes: ['login', 'login_legacy']
            methods: ['POST']
            on_failure: flash_redirect
            message: 'Security verification failed. Please try again.'
{{ turnstile_widget('login') }}

A few details that matter:

  • List every route that reaches the form, legacy and prefixed ones included, or a post to the old URL skips the captcha.
  • The token is checked server-side. The guard POSTs the secret, the token and the client IP to Cloudflare's siteverify endpoint, then checks success, the expected action and, if configured, the hostname. Per Cloudflare's docs, a token is single-use and expires after 300 seconds.
  • It fails closed if Cloudflare is unreachable. A captcha that opens when its verifier is down isn't doing anything.
  • It ships off. TURNSTILE_ENABLED=0 by default, and an empty secret also disables it, so a fresh clone or review app isn't locked out of its own login page. A deploy that forgets the secret looks installed and does nothing.
  • Add challenges.cloudflare.com to script-src, frame-src and connect-src if the app sends a CSP.

The first login after deploy, and the end-to-end check

Shipped together, the layers stack. An admin's first login can hit IP approval, then a mailed code, then a forced password change before they see a single page. With real users, I switch them on in this order: the allowlist and break-glass first, with the reviewers' own addresses pre-approved, then a check that a real admin can still log in, then 2FA, then rotation with whatever grace period the client chose. Tell people before each step.

The interesting failures are at the seams, so once everything is in I walk the whole chain against the running app:

  1. An unapproved IP requesting /admin is refused without a session cookie being set.
  2. From an approved IP, a correct password lands on the 2FA challenge, not the dashboard.
  3. While the code is pending, / and /admin both redirect to the challenge, and the login log has a 2FA-pending row.
  4. After the right code, an expired password redirects to change-password; a fresh one goes straight through.
  5. Logout works from the challenge and change-password pages.
  6. The Set-Cookie header carries the new cookie name and Max-Age=86400.
  7. A request with a forged X-Forwarded-For is still refused, and a pre-flush session ID gets no access under either cookie name.
  8. The login log rows from those steps show the client's location, not the proxy's. That's the cheapest proof trusted_proxies is right.
bin/console debug:event-dispatcher kernel.request | head -20
curl -sk -o /dev/null -D - https://admin.example.test/login | grep -i set-cookie

Then remove any temporary IP block someone added to public/index.php during the incident, and run step 2 again. If it still works, you've proved the allowlist is doing the job.

I keep each layer as a written playbook next to a working reference implementation, so porting it to the next app is mostly adapting names. Same idea as giving an AI coding agent real Symfony context: the traps are written down where the agent will read them.

FAQ

Is a Symfony IP allowlist enough on its own?

No. It decides who can reach the admin login page, and a sprayed password still works from an approved office address. That's what 2FA is for. The allowlist is what stops a forged cookie from an unapproved address.

Why use email for 2FA instead of an authenticator app?

Email is the weaker second factor, and I say so. It's a sensible start when password reset already relies on email, and it still makes a sprayed password useless alone. SchebTwoFactorBundle's TOTP provider uses the same wiring if you want it later.

Does renaming the session cookie invalidate stolen sessions?

No. Browsers lose the old cookie, but the session data is still on the server, and anyone holding a stolen ID can send it under the new name. To invalidate sessions, empty the session store (or move save_path) and rotate the secret that signs remember-me cookies.

How long does hardening a Symfony admin like this take?

The flush is quick. After that, each layer is its own piece of work. The allowlist is the largest, with its admin screens, emailed review flow, fingerprinting and geo backfill. A staged rollout adds calendar time on top, because each step should settle before the next goes live.

Need a Symfony or Laravel login locked down?

I've built PHP, Laravel, Symfony and React applications for US brands for 15 years, and admin hardening like this is work I've done on live production apps, including after an incident.

If you're not sure where your admin stands, I offer a one-day auth audit of a Symfony admin: login flow, security.yaml, sessions, proxies and rate limits, with a written list of what to fix first. If your company's admin panel needs the full treatment, or you're an agency with a client app that just had a scare, I can do the work directly or white-label under your name. See what I take on, or send me a short note about your setup and I'll reply within one business day with where I'd start.