Wednesday, January 31, 2018

PHP generates JWT

This script generates basic JWT token

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
$decode = file_get_contents('php://input');
$arr = json_decode($decode, true);
if ($arr['email'] == 'me@example.com' && $arr['password'] == '123') {
    $key = 'very-secret-value-only-on-server';
    // header
    $h = ["alg" => "HS256", "typ" => "JWT"];
    $h = base64_encode(json_encode($h));
     
    //payload
    $p = ["username" => "username", "role" => "admin"];
    $p = base64_encode(json_encode($p));
     
    // encryption and signing
    $signature = hash_hmac('sha256', "$h.$p", $key, true);
    $signature = base64_encode($signature);
 
    $token = "$h.$p.$signature";
    echo $token;
}

You should add iat and exp to payload. Debugger for JWT.