Skip to content

Different Template per Firewall

Warning: You are browsing the documentation for version 5.x which is not maintained anymore. If some of your projects are still using this version, consider upgrading.

Different Template per Firewall

You're using two-factor authentication on multiple firewalls and you need to render the form differently for each firewall. Here's a basic solution for you:

Create a new form renderer class like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php

namespace Acme\Demo;

use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\TwoFactorFormRendererInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\FirewallMapInterface;
use Twig\Environment;

class CustomFormRenderer implements TwoFactorFormRendererInterface
{
    private $twigEnvironment;
    private $firewallMap;
    private $templates; // Map of [firewall name => template path]

    public function __construct(
        Environment $twigRenderer,
        FirewallMapInterface $firewallMap,
        array $templates
    ) {
        $this->twigEnvironment = $twigRenderer;
        $this->firewallMap = $firewallMap;
        $this->templates = $templates;
    }

    public function renderForm(Request $request, array $templateVars): Response
    {
        $firewallName = $this->firewallMap->getFirewallConfig($request)->getName();
        $template = $this->templates[$firewallName];

        $content = $this->twigEnvironment->render($template, $templateVars);
        $response = new Response();
        $response->setContent($content);

        return $response;
    }
}

Register it as a service:

1
2
3
4
5
6
7
8
9
# config/services.yaml
services:
    acme.custom_form_renderer:
        class: Acme\Demo\CustomFormRenderer
        arguments:
            - '@twig'
            - '@security.firewall.map'
            # This is a map of firewall name to template path
            - { main: 'security/2fa_google.html.twig', admin: 'admin/security/2fa_google.html.twig' } ]

Configure the new service as the form renderer:

1
2
3
4
5
# config/packages/scheb_2fa.yaml
scheb_two_factor:
    google:  # Or "totp" or "email", depending on the two-factor provider you're using
        enabled: true
        form_renderer: acme.custom_form_renderer
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version