Mikael Svensson
Mikael Svensson

Reputation: 107

How to create a refresh token in plain php?

I've been searching the web for an example/explanation on how to generate a refresh token myself. Not using any services like Oauth etc. Just in plain php. I found many info on how to use them, but not how to create one.

I create a JWT like this:

$secret = "secret";

$header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);

function createJWT($user_id){
    $date = new DateTime();
    $timestamp = $date->getTimestamp();

    global $header;
    global $secret;
    $payload = ['user_id' => $user_id, 'iat'=> $timestamp, 'exp'=>$timestamp+10];
    $payload = json_encode( $payload );
    $base64UrlHeader = str_replace(['+','/','='], ['-','_',''], base64_encode($header));
    $base64UrlPayload = str_replace(['+','/','='], ['-','_',''], base64_encode($payload));
    $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $secret);
    $base64UrlSignature = str_replace(['+','/','='], ['-','_',''], base64_encode($signature));
    $JWT =$base64UrlHeader . '.' . $base64UrlPayload . '.' . $base64UrlSignature;

    return $JWT;
}

And when looking at the jwt.io debugger it works fine.

But since I want to use a refresh token so I can "create" more access tokens after they've expired I can't find any information on how to create such one.

What i understand the access token is stored in local storage/cookie while the refresh token is store in a database.

How do I create a refresh token, what info does it contain? I guess it's not just a random string. And what does the schema a of the database/table storing the refresh token look like?

Upvotes: 2

Views: 9451

Answers (1)

Mikael Svensson
Mikael Svensson

Reputation: 107

I looked into the docs of JWT and it seemed like you just have to create a uuid, guid wich is just a uniq valu/string that's nearly impossible to hack.

I tooked that uuid and stored it in local storage as "refresh-token". And I also stored in in a DB with a table containing: ID | user_id | refresh-token | expireDate So whenever the JWT had expired I use the long-lasting refresh token and check if that refresh token was present in the db and if it was not expired. Then I sent back a new JWT along with a new refresh token.

Upvotes: 5

Related Questions