php
50 lines · 9 steps
Verifying an HS256 JWT in PHP
A step-by-step walk through splitting, decoding, and cryptographically validating a JSON Web Token signed with HMAC-SHA256.
Explained by
highlit
1<?php
2
3function verifyJwt(string $token, string $secret): array
4{
5 $segments = explode('.', $token);
6 if (count($segments) !== 3) {
7 throw new InvalidArgumentException('Token must have three segments');
8 }
9
10 [$encodedHeader, $encodedPayload, $encodedSignature] = $segments;
11
12 $header = json_decode(base64UrlDecode($encodedHeader), true);
13 $payload = json_decode(base64UrlDecode($encodedPayload), true);
14
15 if (!is_array($header) || ($header['alg'] ?? null) !== 'HS256') {
16 throw new RuntimeException('Unsupported or missing algorithm');
17 }
18
19 $expected = hash_hmac('sha256', "$encodedHeader.$encodedPayload", $secret, true);
20 $provided = base64UrlDecode($encodedSignature);
21
22 if (!hash_equals($expected, $provided)) {
23 throw new RuntimeException('Signature verification failed');
24 }
25
26 $now = time();
27 if (isset($payload['exp']) && $now >= (int) $payload['exp']) {
28 throw new RuntimeException('Token has expired');
29 }
30 if (isset($payload['nbf']) && $now < (int) $payload['nbf']) {
31 throw new RuntimeException('Token not yet valid');
32 }
33
34 return $payload;
35}
36
37function base64UrlDecode(string $input): string
38{
39 $remainder = strlen($input) % 4;
40 if ($remainder) {
41 $input .= str_repeat('=', 4 - $remainder);
42 }
43
44 $decoded = base64_decode(strtr($input, '-_', '+/'), true);
45 if ($decoded === false) {
46 throw new RuntimeException('Invalid base64url encoding');
47 }
48
49 return $decoded;
50}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A JWT's signature covers the encoded header and payload joined by a dot, so recomputing the HMAC over that exact string is how you prove integrity.
- 2Always compare signatures with a constant-time function like hash_equals to avoid leaking information through timing.
- 3Decoding a token is not trusting it — pinning the algorithm and checking exp and nbf are essential to prevent forged or stale tokens.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/verifying-an-hs256-jwt-in-php-explained-php-6a52/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.