OAuth 2.0 and JWT Authorization in PHP: A Complete Guide for Beginners

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\n

Modern web applications rarely do without authorization systems. The two most popular protocols — OAuth 2.0 and JWT (JSON Web Token) — allow developers to create secure and scalable solutions. In this article, we will explore how to implement OAuth 2.0 and JWT authorization in PHP from scratch. The material is aimed at beginners, so all concepts will be explained in simple language with practical examples.

\n\n

OAuth 2.0 is a delegated access protocol. It allows users to grant third parties limited access to their resources without sharing their password. JWT, in turn, is a compact token format that contains all the necessary information about the user and their permissions.

\n\n

What is JWT and how does it work?

\n\n

JWT (JSON Web Token) is an open standard (RFC 7519) that defines a compact and self-contained way to transmit information between parties as a JSON object. The token consists of three parts separated by dots:

\n\n
    \n
  • Header — contains information about the token type and the encryption algorithm (usually HS256 or RS256).
  • \n
  • Payload — contains "claims": user data, issue time (iat), expiration time (exp), and others.
  • \n
  • Signature — a signature created based on the header, payload, and a secret key. It guarantees data integrity.
  • \n
\n\n

Here is what a typical JWT looks like:

\n\n
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6ItCQ0L3QsNGC0L7Qu9C40LkiLCJpYXQiOjE1MTYyMzkwMjJ9.4vGJ7qF6b0Q9l8z3X5p2Rk1h7t9y2w4z6x8c0v2b4n6m8
\n\n

The advantage of JWT is that the server does not need to store sessions in the database — all the information is already encoded in the token. This makes the system easily scalable.

\n\n

Installing the library for working with JWT in PHP

\n\n

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

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

Creating and verifying a JWT token

\n\n

Let's look at a basic example of creating a token when a user logs in and verifying it when accessing a protected resource.

\n\n

1. Token generation (login.php):

\n\n
<?php\nrequire_once 'vendor/autoload.php';\n\nuse Firebase\\JWT\\JWT;\nuse Firebase\\JWT\\Key;\n\n$secretKey = 'your-secret-key-at-least-32-characters-long';\n\n// User data after successful authentication\n$payload = [\n    'iss' => 'pythonlib.ru',        // Token issuer\n    'sub' => $userId,              // User ID\n    'name' => $userName,           // User name\n    'role' => 'user',              // Role\n    'iat' => time(),               // Issued at time\n    'exp' => time() + 3600         // Token expires in 1 hour\n];\n\n$jwt = JWT::encode($payload, $secretKey, 'HS256');\n\n// Send the token to the client\necho json_encode(['token' => $jwt]);\n?>
\n\n

2. Token verification (profile.php):

\n\n
<?php\nrequire_once 'vendor/autoload.php';\n\nuse Firebase\\JWT\\JWT;\nuse Firebase\\JWT\\Key;\n\n$secretKey = 'your-secret-key-at-least-32-characters-long';\n\n// Get the token from the Authorization header\n$headers = getallheaders();\n$authHeader = $headers['Authorization'] ?? '';\n\nif (preg_match('/Bearer\\s(\\S+)/', $authHeader, $matches)) {\n    $jwt = $matches[1];\n    \n    try {\n        $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));\n        \n        // Token is valid, get user data\n        $userId = $decoded->sub;\n        $userName = $decoded->name;\n        \n        // Return protected data\n        echo json_encode(['status' => 'success', 'user' => $decoded]);\n        \n    } catch (Exception $e) {\n        // Token is invalid or expired\n        htt                

Blogs

Book Recommendations