Generating JWT tokens in php

A JWT token mainly consists of Header, payload, signature


<?php


function generate_jwt($headers, $payload, $secret = 'secret') {

$headers_encoded = base64url_encode(json_encode($headers));

$payload_encoded = base64url_encode(json_encode($payload));

$signature = hash_hmac('SHA256', "$headers_encoded.$payload_encoded", $secret, true);

$signature_encoded = base64url_encode($signature);

$jwt = "$headers_encoded.$payload_encoded.$signature_encoded";

return $jwt;

} ?>


In this function where we are generating a JWT token requires to pass headers and payload variables which we are generating as shown below:

$headers = array('alg'=>'HS256','typ'=>'JWT');

$payload = array('sub'=>'1234567890','name'=>'John Doe', 'admin'=>true, 'exp'=>(time() + 60));


$jwt = generate_jwt($headers, $payload);


Thus we can generate a JWT token in php

Sign In or Register to comment.