0

I had created JWT in php.I had found the way to create JWT from following link.

JWT (JSON Web Token) in PHP without using 3rd-party library. How to sign?

<?php
//build the headers
$headers = ['alg'=>'HS256','typ'=>'JWT'];
$headers_encoded = base64_encode(json_encode($headers));

//build the payload
$payload = ['sub'=>'1234567890','name'=>'John Doe', 'admin'=>true];
$payload_encoded = base64_encode(json_encode($payload));

//build the signature
$key = 'secret';
$signature = hash_hmac('SHA256',"$headers_encoded.$payload_encoded",$key,true);
$signature_encoded = base64_encode($signature);

//build and return the token
$token = "$headers_encoded.$payload_encoded.$signature_encoded";
echo $token;
?>

Now how can i authenticate it. I am sending token from Android but i want to validate that this is proper token or not. So how can i do it in code before fulfilling the request.

Should i store token in database?

And is it proper way to give security to api?

Community
  • 1
  • 1
Naitik Kundalia
  • 199
  • 1
  • 1
  • 19

2 Answers2

0

I highly recommend using a well known JWT library for this. This is cryptography, and rolling your own crypto is usually dangerous. There are a few packages around with widespread adoption that have been vetted by security professionals.

If you are going to do this manually, at least take inspiration from one of these packages to ensure that you're doing it correctly: https://github.com/firebase/php-jwt/blob/master/src/JWT.php#L69-L138

The linked code is pretty easy to follow. Essentially you're:

  1. Decoding the token by splitting on ., base64_decodeing, and then json_decodeing.
  2. Checking the signature of the provided JWT against one that is computed again from the decoded header and payload. The alg header property in your example will tell you what algorithm to use to check the signature.
Chris White
  • 865
  • 1
  • 9
  • 20
0

Short solution for your example :

    public function verify(string $token, string $secret): bool
    {
        [$headerEncoded, $bodyEncoded, $signatureEncoded] = explode('.', $token);
        $signature = base64_decode($signatureEncoded);

        $hash = hash_hmac('sha256', implode('.', [$headerEncoded, $bodyEncoded]), $secret, true);

        return \hash_equals($signature, $hash);
    }

But you sohuld encode and decode string with URL-Safe Base64.

Fabien Salles
  • 1,101
  • 15
  • 24