Cookbook

Security Guide

Practical security patterns for authentication, CSRF, rate limiting, headers, and production hardening.

This page focuses on the parts of Glueful security that are both implemented in the framework and useful in day-to-day application code. Standalone snippets assume you already have an ApplicationContext available as $context.

What Glueful Covers

  • JWT-based authentication with persisted sessions
  • CSRF protection for browser-based flows
  • Rate limiting and abuse controls
  • Security middleware and headers
  • Production hardening and security CLI commands

Authentication and Sessions

Glueful’s authentication flow is centered around the auth manager, token manager, and session store.

use Glueful\Auth\Interfaces\SessionStoreInterface;
use Glueful\Auth\TokenManager;

$store = container($context)->get(SessionStoreInterface::class);
$tokenManager = app($context, TokenManager::class);

$user = [
    'uuid' => $userUuid,
    'email' => $email,
    'username' => $username,
];

$accessTtl = $store->getAccessTtl('jwt', false);
$refreshTtl = $store->getRefreshTtl('jwt', false);
$tokens = $tokenManager->generateTokenPair($user, $accessTtl, $refreshTtl);

$store->create($user, $tokens, 'jwt', false);

For authenticated controllers, prefer the built-in BaseController state instead of manually decoding tokens:

use Glueful\Controllers\BaseController;
use Glueful\Http\Response;
use Symfony\Component\HttpFoundation\Request;

final class ProfileController extends BaseController
{
    public function show(Request $request): Response
    {
        if ($this->currentUser === null) {
            return $this->unauthorized('Authentication required');
        }

        return $this->success([
            'user' => $this->currentUser->toArray(),
        ]);
    }
}

Registration and Credential Validation

For custom registration or password reset flows, validate request data before inserting or updating user records.

use Glueful\Controllers\BaseController;
use Glueful\Http\Response;
use Glueful\Helpers\Utils;
use Symfony\Component\HttpFoundation\Request;

final class RegistrationController extends BaseController
{
    public function register(Request $request): Response
    {
        $data = $this->getRequestData();

        if ($error = $this->validateRequest($data, [
            'email' => 'required|email|max:255',
            'password' => 'required|max:255',
        ])) {
            return $error;
        }

        $user = [
            'uuid' => Utils::generateNanoID(),
            'email' => $data['email'],
            'password' => password_hash($data['password'], PASSWORD_BCRYPT),
            'created_at' => date('Y-m-d H:i:s'),
        ];

        $this->db->table('users')->insert($user);

        unset($user['password']);

        return $this->created(['user' => $user]);
    }
}

CSRF Protection

Use CSRF protection for browser forms and cookie-backed SPA flows. Retrieve a token from the built-in endpoint and send it back in a header or form field.

GET /csrf-token

Typical browser request:

POST /profile
X-CSRF-Token: <token>
Cookie: csrf_token=<token>

If you need direct validation outside the built-in middleware, use the request helper and validator stack explicitly.

Rate Limiting

Rate limiting should be stricter on login, OTP, and password reset endpoints than on ordinary authenticated API traffic.

Recommended pattern:

  • Login: low per-minute threshold
  • OTP verification: stricter than login
  • Password reset: low threshold with cooldown
  • Authenticated application traffic: higher user-based limits

See Rate Limiting for route-level examples.

Security Headers and Middleware

Glueful ships with security-oriented middleware that should be enabled in production stacks:

  • auth for JWT/session-backed authentication
  • rate limiting middleware for abuse prevention
  • CSRF middleware for browser-facing writes
  • security headers middleware for CSP, HSTS, frame, and content-type protections

Production baseline:

APP_ENV=production
APP_DEBUG=false
SECURITY_HEADERS_ENABLED=true
CSRF_ENABLED=true
RATE_LIMITING_ENABLED=true
JWT_KEY=replace-with-a-strong-secret

Security Commands

Use the CLI to verify production readiness and inspect vulnerabilities:

php glueful security:scan
php glueful security:vulnerabilities --format=json
php glueful system:production --check --score

Production Checklist

  • Disable debug mode
  • Use HTTPS everywhere
  • Set a strong JWT_KEY
  • Enable security headers
  • Enable rate limiting
  • Restrict admin and internal routes
  • Rotate secrets through environment management, not source control
  • Monitor auth failures and unusual session activity