Search code examples
phplaraveljwtlumen

What's the best way to decode a JWT on Laravel / PHP?


For one of my development, I need to decode a JWT in order to use its information.

I need to do this: https://jwt.io/

Currently, I have written this code but I find it complicated for this need.

$token = $request->bearerToken();

try {
    $jwtParts = explode('.', $token);
    if (empty($header = $jwtParts[0]) || empty($payload = $jwtParts[1]) || empty($jwtParts[2])) {
        throw new JwtServiceException('Missing JWT part(s).');
    }
} catch (Throwable $e) {
    throw new JwtServiceException('Provided JWT is invalid.', $e);
}

if (
    !($header = base64_decode($header))
    || !($payload = base64_decode($payload))
) {
    throw new JwtServiceException('Provided JWT can not be decoded from base64.');
}

if (
    empty(($header = json_decode($header, true)))
    || empty(($payload = json_decode($payload, true)))
) {
    throw new JwtServiceException('Provided JWT can not be decoded from JSON.');
}

Result:

enter image description here

The code works but I want something more readable.

I tested the Jwt firebase library but this one does not allow me to decode a JWT string.

Thank's you so much in advance for your help


Solution

  • You can use this package https://github.com/lcobucci/jwt to handle your jwt. It already provides a lot of tools. If you're using Passport in your Lumen app it should be probably already available.