---
title: 'Custom Admin Page with Twig and CSRF Protection'
url: 'http://phramecms.org/cookbook/custom-admin-page-with-twig'
markdown_url: 'http://phramecms.org/cookbook/custom-admin-page-with-twig.md'
bundle: recipe
category: admin-ui
difficulty: intermediate
packages_used:
  - phramecms/core
  - phramecms/routing
  - phramecms/user
  - phramecms/admin
summary: 'Build a session-authenticated, RBAC-guarded, CSRF-protected Admin UI page with a sidebar menu item, module Twig namespace, AdminResponder::renderPage(), and an in-process HTTP test.'
source: 'https://github.com/PhrameCMS/docs/blob/main/cookbook/custom-admin-page-with-twig.md'
updated_at: '2026-12-04T21:49:38+00:00'
---

# Custom Admin Page with Twig and CSRF Protection

This recipe adds a custom `/admin/acme/tools` page to the PhrameCMS Admin UI that inherits the active Admin theme, appears automatically in the permission-filtered sidebar, enforces RBAC via `PolicyEnforcerInterface::assertAllowed()`, and handles a CSRF-protected `POST` action.

## Security Checklist

Every custom Admin UI route MUST follow three strict rules:

1. **Always pair `meta: ['auth' => 'session']` with `middlewares: [AdminModule::SESSION_AUTH_MIDDLEWARE_SERVICE]`**. Setting `meta: ['auth' => 'session']` without attaching `AdminModule::SESSION_AUTH_MIDDLEWARE_SERVICE` tells global `BearerAuthMiddleware` to hand off authentication — leaving the route completely unauthenticated if the middleware is omitted!
2. **Enforce permissions inside the controller** using `PolicyEnforcerInterface::assertAllowed()` (or by delegating to `OperationBus`). `AdminMenuItem::$requiredPermission` hides the sidebar link, but direct URL requests must still be authorized.
3. **Include `<input type="hidden" name="_csrf" value="{{ csrf_token }}">` on every `<form method="post">`**. `SessionAuthMiddleware` automatically rejects any `POST`, `PUT`, `PATCH`, or `DELETE` request lacking a valid `_csrf` body field or `X-CSRF-Token` header with HTTP `403`.

---

## Step 1: Add Sidebar Navigation (`AdminMenuProviderInterface`)

Create `src/Admin/ToolsMenuProvider.php`:

```php
<?php

declare(strict_types=1);

namespace Acme\Tools\Admin;

use PhrameCms\Admin\Contract\AdminMenuProviderInterface;
use PhrameCms\Admin\Navigation\AdminMenuItem;

final readonly class ToolsMenuProvider implements AdminMenuProviderInterface
{
    /** @return list<AdminMenuItem> */
    public function items(): array
    {
        return [
            new AdminMenuItem(
                id: 'acme.tools.index',
                label: 'Maintenance Tools',
                path: '/admin/acme/tools',
                group: 'Extensions',
                weight: 50,
                requiredPermission: 'acme.tools.manage',
            ),
        ];
    }
}
```

---

## Step 2: Register a Module Twig Namespace & Page Template

Create `src/Admin/ToolsTemplateNamespaceProvider.php`:

```php
<?php

declare(strict_types=1);

namespace Acme\Tools\Admin;

use PhrameCms\Admin\Contract\AdminTemplateNamespaceProviderInterface;

final readonly class ToolsTemplateNamespaceProvider implements AdminTemplateNamespaceProviderInterface
{
    /** @return array<string, string> */
    public function namespaces(): array
    {
        return [
            'acme_tools' => dirname(__DIR__, 2) . '/templates',
        ];
    }
}
```

Create `templates/tools.html.twig` extending `layout.html.twig` (which automatically inherits the active theme, topbar, sidebar `nav_groups`, and `csrf_token` populated by `AdminResponder::renderPage()`):

```twig
{% extends 'layout.html.twig' %}

{% block content %}
    {% if notice is not null %}
        <div class="alert alert-success" role="status">{{ notice }}</div>
    {% endif %}

    <section class="card">
        <h2>Cache &amp; Index Maintenance</h2>
        <p>Current runs recorded in this process: <strong>{{ run_count }}</strong></p>

        <form method="post" action="/admin/acme/tools/rebuild">
            <input type="hidden" name="_csrf" value="{{ csrf_token }}">
            <div class="form-field">
                <label class="form-label" for="rebuild_reason">Reason</label>
                <input class="form-input" id="rebuild_reason" type="text" name="reason" value="" required>
            </div>
            <button type="submit" class="btn btn-primary">Trigger Rebuild</button>
        </form>
    </section>
{% endblock %}
```

---

## Step 3: Implement the Admin Controller

Create `src/Admin/ToolsController.php`. Depend only on `AdminResponder` (never on Twig directly — preserving the hexagonal boundary) and authorize every handler via `PolicyEnforcerInterface::assertAllowed()`:

```php
<?php

declare(strict_types=1);

namespace Acme\Tools\Admin;

use PhrameCms\Admin\Http\AdminResponder;
use PhrameCms\Core\Contract\ActorInterface;
use PhrameCms\Core\Contract\PolicyEnforcerInterface;
use PhrameCms\Core\Exception\AuthorizationException;
use PhrameCms\User\Http\BearerAuthMiddleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final class ToolsController
{
    private int $runCount = 0;

    public function __construct(
        private readonly AdminResponder $responder,
        private readonly PolicyEnforcerInterface $policyEnforcer,
    ) {}

    public function index(ServerRequestInterface $request): ResponseInterface
    {
        if ($denied = $this->authorize($request, 'acme.tools.view')) {
            return $denied;
        }

        $query = $request->getQueryParams();
        $notice = ($query['rebuilt'] ?? null) === '1'
            ? 'Maintenance rebuild completed.'
            : null;

        return $this->responder->renderPage(
            request: $request,
            template: '@acme_tools/tools.html.twig',
            pageTitle: 'Maintenance Tools',
            context: [
                'notice' => $notice,
                'run_count' => $this->runCount,
            ],
        );
    }

    public function rebuild(ServerRequestInterface $request): ResponseInterface
    {
        // SessionAuthMiddleware has already verified the session cookie and CSRF token.
        if ($denied = $this->authorize($request, 'acme.tools.rebuild')) {
            return $denied;
        }

        $body = $request->getParsedBody();
        $reason = is_array($body) && is_string($body['reason'] ?? null) ? trim($body['reason']) : '';
        if ($reason === '') {
            return $this->responder->error(
                request: $request,
                status: 422,
                title: 'Validation Failed',
                message: 'A maintenance reason is required.',
            );
        }

        $this->runCount++;

        return $this->responder->redirect('/admin/acme/tools?rebuilt=1');
    }

    private function authorize(ServerRequestInterface $request, string $operation): ?ResponseInterface
    {
        $actor = $request->getAttribute(BearerAuthMiddleware::ACTOR_ATTRIBUTE);
        if (!$actor instanceof ActorInterface) {
            return $this->responder->error($request, 401, 'Unauthorized', 'Authentication required.');
        }

        try {
            $this->policyEnforcer->assertAllowed($actor, $operation, ['acme.tools.manage']);
        } catch (AuthorizationException $e) {
            return $this->responder->error($request, 403, 'Forbidden', $e->getMessage());
        }

        return null;
    }
}
```

---

## Step 4: Register Session-Protected Routes & Wire the Module

Create `src/Routing/ToolsRouteProvider.php`:

```php
<?php

declare(strict_types=1);

namespace Acme\Tools\Routing;

use Acme\Tools\Admin\ToolsController;
use PhrameCms\Admin\AdminModule;
use PhrameCms\Routing\Contract\RouteProviderInterface;
use PhrameCms\Routing\Route;
use PhrameCms\Routing\RouteCollection;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class ToolsRouteProvider implements RouteProviderInterface
{
    public function __construct(
        private ToolsController $controller,
    ) {}

    public function registerRoutes(RouteCollection $routes): void
    {
        $routes->add(new Route(
            name: 'acme.admin.tools.index',
            methods: ['GET'],
            path: '/admin/acme/tools',
            handler: fn(ServerRequestInterface $r): ResponseInterface => $this->controller->index($r),
            middlewares: [AdminModule::SESSION_AUTH_MIDDLEWARE_SERVICE],
            meta: ['auth' => 'session'],
        ));

        $routes->add(new Route(
            name: 'acme.admin.tools.rebuild',
            methods: ['POST'],
            path: '/admin/acme/tools/rebuild',
            handler: fn(ServerRequestInterface $r): ResponseInterface => $this->controller->rebuild($r),
            middlewares: [AdminModule::SESSION_AUTH_MIDDLEWARE_SERVICE],
            meta: ['auth' => 'session'],
        ));
    }
}
```

Wire all four components in `src/ToolsModule.php`:

```php
<?php

declare(strict_types=1);

namespace Acme\Tools;

use Acme\Tools\Admin\ToolsController;
use Acme\Tools\Admin\ToolsMenuProvider;
use Acme\Tools\Admin\ToolsTemplateNamespaceProvider;
use Acme\Tools\Routing\ToolsRouteProvider;
use PhrameCms\Admin\AdminModule;
use PhrameCms\Admin\Contract\AdminMenuProviderInterface;
use PhrameCms\Admin\Contract\AdminTemplateNamespaceProviderInterface;
use PhrameCms\Core\Contract\ContainerBuilderInterface;
use PhrameCms\Core\Contract\ModuleInterface;
use PhrameCms\Routing\Contract\RouteProviderInterface;
use Psr\Container\ContainerInterface;

final readonly class ToolsModule implements ModuleInterface
{
    public const string NAME = 'acme.tools';

    public function name(): string
    {
        return self::NAME;
    }

    /** @return list<string> */
    public function dependencies(): array
    {
        return [AdminModule::NAME];
    }

    public function register(ContainerBuilderInterface $builder): void
    {
        $builder->autowire(ToolsController::class);
        $builder->autowire(ToolsMenuProvider::class, [AdminMenuProviderInterface::SERVICE_TAG]);
        $builder->autowire(
            ToolsTemplateNamespaceProvider::class,
            [AdminTemplateNamespaceProviderInterface::SERVICE_TAG],
        );
        $builder->autowire(ToolsRouteProvider::class, [RouteProviderInterface::SERVICE_TAG]);
    }

    public function boot(ContainerInterface $container): void {}
}
```

---

## Step 5: Test Session Auth, CSRF, RBAC, and HTML Output In-Process

```php
<?php

declare(strict_types=1);

namespace Acme\Tools\Tests;

use Acme\Tools\ToolsModule;
use Nyholm\Psr7\ServerRequest;
use PhrameCms\Admin\AdminModule;
use PhrameCms\Config\ConfigModule;
use PhrameCms\Core\Kernel;
use PhrameCms\Core\Operation\ExecutionContext;
use PhrameCms\Core\Operation\OperationBus;
use PhrameCms\Core\Operation\OperationRequest;
use PhrameCms\Core\Security\ActorType;
use PhrameCms\Database\DatabaseModule;
use PhrameCms\Database\Schema\SchemaInstallRunner;
use PhrameCms\Entity\EntityModule;
use PhrameCms\Routing\HttpKernel;
use PhrameCms\Routing\RoutingModule;
use PhrameCms\User\Http\SessionCookie;
use PhrameCms\User\Security\AuthenticatedActor;
use PhrameCms\User\Security\SessionManager;
use PhrameCms\User\UserModule;
use PHPUnit\Framework\TestCase;

final class ToolsAdminPageTest extends TestCase
{
    public function testSessionAuthCsrfAndRbacEnforcement(): void
    {
        $kernel = new Kernel([
            new DatabaseModule('memory://'),
            new ConfigModule(),
            new RoutingModule(),
            new UserModule(),
            new EntityModule(),
            new AdminModule(),
            new ToolsModule(),
        ]);
        $kernel->boot();

        $container = $kernel->container();
        $container->getTyped(SchemaInstallRunner::class, SchemaInstallRunner::class)->installAll();

        $bus = $container->getTyped(OperationBus::class, OperationBus::class);
        $http = $container->getTyped(HttpKernel::class, HttpKernel::class);
        $sessions = $container->getTyped(SessionManager::class, SessionManager::class);
        $system = new AuthenticatedActor(id: 'system', type: ActorType::System, scopes: ['*']);
        $ctx = new ExecutionContext($system, 'admin-page-test');

        // Seed role and human user with acme.tools.manage
        $bus->execute(new OperationRequest('role.create', [
            'id' => 'role_ops',
            'name' => 'ops',
            'label' => 'Operations',
            'permissions' => ['acme.tools.manage'],
        ], $ctx));
        $bus->execute(new OperationRequest('user.create', [
            'username' => 'alice',
            'email' => 'alice@example.test',
            'password' => 'test-passphrase-123',
            'role_ids' => ['role_ops'],
        ], $ctx));

        // 1. Unauthenticated GET redirects 302 -> /admin/login
        $anon = $http->handle(new ServerRequest('GET', '/admin/acme/tools'));
        self::assertSame(302, $anon->getStatusCode());
        self::assertSame('/admin/login', $anon->getHeaderLine('Location'));

        // Sign in to obtain session cookie + CSRF token
        $issued = $sessions->loginWithPassword('alice', 'test-passphrase-123');
        $cookie = [SessionCookie::DEFAULT_NAME => $issued->plaintextToken];

        // 2. Authenticated GET renders the page and sidebar link
        $page = $http->handle((new ServerRequest('GET', '/admin/acme/tools'))->withCookieParams($cookie));
        self::assertSame(200, $page->getStatusCode());
        $html = (string) $page->getBody();
        self::assertStringContainsString('Maintenance Tools', $html);
        self::assertStringContainsString($issued->session->csrfToken, $html);

        // 3. POST without CSRF token returns 403 Forbidden
        $noCsrf = $http->handle(
            (new ServerRequest('POST', '/admin/acme/tools/rebuild'))
                ->withCookieParams($cookie)
                ->withParsedBody(['reason' => 'No token']),
        );
        self::assertSame(403, $noCsrf->getStatusCode());

        // 4. POST with valid CSRF token redirects back with notice
        $okPost = $http->handle(
            (new ServerRequest('POST', '/admin/acme/tools/rebuild'))
                ->withCookieParams($cookie)
                ->withParsedBody([
                    '_csrf' => $issued->session->csrfToken,
                    'reason' => 'Nightly cache clear',
                ]),
        );
        self::assertSame(302, $okPost->getStatusCode());
        self::assertSame('/admin/acme/tools?rebuilt=1', $okPost->getHeaderLine('Location'));
    }
}
```

## Related Documentation

- [Custom Modules Guide](../guides/custom-modules.md) — HTTP routing security conventions and Twig override precedence.
- [Security & Production Hardening](../guides/security-production.md) — Session cookie flags, CSP headers, and reverse-proxy configuration.
- [Service Tags Reference](../reference/service-tags.md) — Details for `phrame.admin_menu`, `phrame.admin_template_namespace`, and `phrame.route_provider`.
