OAuth 2.0 and JWT Authorization in PHP: Complete Practical Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to OAuth 2.0 and JWT in PHP

\n

Modern web applications are increasingly moving away from classic session-based authentication in favor of more flexible and scalable solutions. Two key protocols — OAuth 2.0 and JWT (JSON Web Tokens) — have become the de facto standard for authorization in REST APIs, mobile applications, and microservice architecture. In this article, we will use practical examples to break down how to implement OAuth 2.0 and JWT authorization in PHP, using modern libraries and security best practices.

\n

You will learn how to set up an authorization server, issue and verify JWT tokens, organize refresh token issuance, and protect your API endpoints. All code examples are ready to use in your projects.

\n\n

Basics of the OAuth 2.0 Protocol

\n

OAuth 2.0 is an authorization protocol that allows applications to obtain limited access to user resources without sharing their credentials. In the context of a PHP application, OAuth 2.0 is typically implemented via the Authorization Code Grant or the Password Grant for internal services.

\n\n

Key Roles in OAuth 2.0

\n
    \n
  • Resource Owner — the user who owns the data
  • \n
  • Client — the application requesting access (e.g., your PHP frontend)
  • \n
  • Authorization Server — the server that issues tokens
  • \n
  • Resource Server — the server that provides protected resources (your API)
  • \n
\n\n

Token Acquisition Flow via Authorization Code Grant

\n
    \n
  1. The user navigates to the authorization page
  2. \n
  3. After login, the user is redirected back to the application with a temporary code
  4. \n
  5. The PHP server exchanges the code for an access_token and refresh_token
  6. \n
  7. All subsequent API requests are made with the header Authorization: Bearer <access_token>
  8. \n
\n\n

Implementing JWT in PHP with the firebase/php-jwt Library

\n

To work with JWT in PHP, we will use the popular library firebase/php-jwt. Install it via Composer:

\n
composer require firebase/php-jwt
\n\n

Generating a JWT Token

\n

Let's create a function to issue an access token with a payload (claims):

\n
<?php\nuse Firebase\\JWT\\JWT;\nuse Firebase\\JWT\\Key;\n\nfunction generateAccessToken(int $userId, string $email): string {\n    $secretKey = 'your-256-bit-secret-key-here';\n    $issuedAt = time();\n    $expirationTime = $issuedAt + 3600; // 1 hour\n\n    $payload = [\n        'iss' => 'pythonlib.ru',\n        'iat' => $issuedAt,\n        'exp' => $expirationTime,\n        'sub' => $userId,\n        'email' => $email,\n        'roles' => ['user']\n    ];\n\n    return JWT::encode($payload, $secretKey, 'HS256');\n}
\n\n

Verifying a JWT Token

\n

Checking the token's authenticity with each request to a protected resource:

\n
<?php\nfunction validateAccessToken(string $token): ?object {\n    $secretKey = 'your-256-bit-secret-key-here';\n    try {\n        $decoded = JWT::decode($token, new Key($secretKey, 'HS256'));\n        return $decoded;\n    } catch (\\Exception $e) {\n        // Token expired, invalid, or signature mismatch\n        return null;\n    }\n}
\n\n

Middleware for JWT Verification

\n

An example of a simple middleware that can be used with any framework:

\n
<?php\nfunction authMiddleware(): ?object {\n    $headers = getallheaders();\n    $authHeader = $headers['Authorization'] ?? '';\n\n    if (!preg_match('/Bearer\\s(\\S+)/', $authHeader, $matches)) {\n        http_response_code(401);\n        echo json_encode(['error' => 'Token not provided']);\n        exit;\n    }\n\n    $token = $matches[1];\n    $user = validateAccessToken($token);\n\n    if (!$user) {\n        http_response_code(401);\n                

Blogs

Book Recommendations