Generating tokens with slim-jwt-auth

BugHunterUK picture BugHunterUK · Nov 22, 2016 · Viewed 9.4k times · Source

I'm using slim-jwt-auth to create token based authentication for a JSON API.

The docs are very helpful, but one thing I don't understand is how are the tokens generated? The docs say that the middleware is able to decode the token, but can't see any way to encode.

Some projects I've seen use firebase/jwt, but I'm not sure if this is needed, or compatible with slim-jwt-auth.

Is slim-jwt-auth able to generate tokens?

Answer

Mika Tuupola picture Mika Tuupola · Nov 23, 2016

You can but you do not need to install extra libraries to generate the token. The middleware uses firebase/php-jwt internally so you can use the same library to generate the token. Something like the following.

use \Firebase\JWT\JWT;
use \Tuupola\Base62;

$now = new DateTime();
$future = new DateTime("now +2 hours");
$jti = Base62::encode(random_bytes(16));

$secret = "your_secret_key";

$payload = [
    "jti" => $jti,
    "iat" => $now->getTimeStamp(),
    "nbf" => $future->getTimeStamp()
];

$token = JWT::encode($payload, $secret, "HS256");

You might also check the Slim API Skeleton for inspiration.