Security Service Provider
CSRF token manager, middleware and view helper services.
Responsibility
Registers CSRF services used by routes, forms and views: CsrfTokenManager, CsrfMiddleware, CsrfViewHelper and alias csrf pointing to CsrfViewHelper. Token storage depends on SessionInterface, so session configuration must work across requests.
CSRF services
CsrfTokenManager generates, validates, regenerates and forgets named tokens. Tokens are stored in session under _csrf_tokens. CsrfViewHelper exposes token(), field() and fieldName() for rendering forms.
use Lemonade\Framework\Security\Csrf\CsrfTokenManager;
use Lemonade\Framework\Security\Csrf\CsrfViewHelper;
$tokens = $container->get(CsrfTokenManager::class);
$csrf = $container->get('csrf');
$token = $tokens->token();
$field = $csrf->field();
CSRF principle
Generate a token when rendering a form, submit it as a hidden field or X-CSRF-Token header, and validate it for state-changing requests. This protects POST, PUT, PATCH and DELETE requests from cross-site request forgery.
View usage
ViewServiceProvider exposes CSRF in views through shared variable $csrf and through ViewHelpers. Use either the rendered hidden field or the explicit field name/token pair when you need custom markup.
<form method="post" action="<?= e($action) ?>">
<?= $helpers->csrfField() ?>
</form>
<input type="hidden" name="<?= $csrf->fieldName() ?>" value="<?= e($csrf->token()) ?>">
Route middleware
Attach CsrfMiddleware to unsafe routes that mutate state. The middleware reads token from body field LEMONADE_CSRF or header X-CSRF-Token; on mismatch it returns 419 CSRF token mismatch, and on success it regenerates the default token.
use Lemonade\Framework\Security\Csrf\CsrfMiddleware;
$router
->postNamed('contact.submit', '/contact', ContactController::class . '@submit')
->middleware(CsrfMiddleware::class);
Manual validation
Most HTTP forms should use CsrfMiddleware. For custom flows, inject CsrfTokenManager and validate a submitted token directly; handle failure explicitly because the manager only returns a boolean.
use Lemonade\Framework\Security\Csrf\CsrfTokenManager;
final class FormSecurityService
{
public function __construct(
private readonly CsrfTokenManager $tokens,
) {}
public function accepts(string $submittedToken): bool
{
return $this->tokens->validate($submittedToken);
}
}
Form responsibility
The framework does not inject CSRF fields into arbitrary HTML automatically. The form author must render $helpers->csrfField() or an equivalent hidden input and protect the matching unsafe route with CsrfMiddleware.
Security scope
SecurityServiceProvider is not a complete authentication or authorization layer. It covers CSRF services; login flows, identity, roles, permissions and access control are application code or separate providers/middleware.