Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating tokens with slim-jwt-auth

Tags:

php

jwt

slim-3

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?

like image 206
BugHunterUK Avatar asked Nov 22 '16 15:11

BugHunterUK


1 Answers

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.

like image 76
Mika Tuupola Avatar answered Oct 01 '22 22:10

Mika Tuupola