Implementing simple authentication for PHP REST API

Implementing simple authentication for PHP REST API

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Implementing Simple Authentication for PHP REST API

Building a REST API for an internal application on a legacy stack presents unique constraints. When you are forced to run PHP 5.4 with MySQL 5.6, adopting modern standards like OAuth 2.0 often feels like over-engineering the solution. While OAuth provides robust token management and third-party integration capabilities, its complexity is unnecessary if your goal is simply to authenticate a specific internal client against an existing user base.

The proposed architecture involves separating session creation from identity verification. This decoupling allows you to generate a random session identifier without immediately validating credentials, reducing the attack surface for brute-force attacks on the login endpoint itself. However, implementing this securely requires careful attention to database schema design and HTTP security headers.

Database Schema Design

To support this flow, your database needs two primary tables: one for storing user credentials (which you likely already have) and a new table for managing session state. Since you are on MySQL 5.6, ensure your InnoDB engine is enabled for transactional integrity.

Create a sessions table that stores the random ID and links it to a user only after successful authentication:

CREATE TABLE sessions (
    id VARCHAR(64) PRIMARY KEY,
    user_id INT UNSIGNED NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    expires_at TIMESTAMP NOT NULL,
    INDEX idx_user_id (user_id),
    INDEX idx_expires (expires_at)
);

The id column should hold a cryptographically secure random string. In PHP 5.4, the standard random_bytes() function might not be available depending on your exact build; if necessary, use mt_rand() combined with base62 encoding or a dedicated entropy source, though this is less ideal. A better approach in constrained environments is to rely on openssl_random_pseudo_bytes().

The Login Endpoint

The login endpoint must handle three distinct phases: validation, association, and rate limiting. Never compare passwords directly; always hash them using a slow algorithm like bcrypt or scrypt. Given the legacy environment, ensure your password hashing function is compatible with PHP 5.4.

Crucially, this endpoint must be rate-limited. A simple approach is to track failed login attempts per IP address or user ID in a temporary table for a specific window (e.g., 15 minutes). If failures exceed a threshold (say, 5), block further requests temporarily. This prevents an attacker from iterating through password hashes regardless of how many sessions exist.

// Pseudocode logic for the login endpoint
if ($sessionExists = checkSession($sessionId)) {
    $user = authenticateUser($username, $password);
    
    if ($user) {
        // Rate limit check here before proceeding
        updateSession($sessionId, ['user_id' => $user->id]);
        return response()->json(['status' => 'authenticated']);
    } else {
        triggerRateLimit();
    }
}

Session State Management and Expiration

Storing the session ID alone is insufficient. You must enforce expiration to mitigate the risk of stolen tokens sitting in a database indefinitely. Set expires_at to a reasonable duration, such as 24 hours or one week, depending on your internal app's security posture.

On every subsequent request to protected endpoints, the server must verify two conditions before processing:

  1. Does the id exist in the sessions table?
  2. Has expires_at passed?

If either condition fails, invalidate the session and return a 401 Unauthorized response. This stateless verification logic keeps your application lightweight without requiring complex token signing libraries.

Logout and Security Headers

The logout endpoint is straightforward: it simply deletes the record from the sessions table using the provided ID. However, because you are running over HTTPS, you must strictly enforce the Secure flag on all cookies if you decide to use them for session persistence. If relying solely on opaque tokens in the query parameters or headers (which is common in stateless APIs), ensure you validate the token signature or existence on every request.

Additionally, always send the Content-Security-Policy and X-Frame-Options: DENY headers to protect against clickjacking attacks, especially since this API serves an internal app that might be embedded in other dashboards.

Why Not OAuth?

OAuth 2.0 introduces flow complexity (authorization codes, refresh tokens, scopes) that adds significant implementation overhead. For an internal tool where you control the client and the server, a custom session-based approach is acceptable if you rigorously implement rate limiting, expiration, and secure transmission. The trade-off is that your custom solution lacks built-in features like token introspection endpoints, but for your specific use case, simplicity wins.

If you eventually outgrow PHP 5.4 constraints or require more sophisticated security guarantees, migrating to a modern framework with built-in support for these patterns would be the natural next step.

Our network