Wednesday, January 31, 2018

PHP generates JWT

This script generates basic JWT token

<?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.

No comments:

Post a Comment