codecasts / laravel-jwt

Dead simple, plug and play JWT API Authentication for Laravel (5.4+)
MIT License
234 stars 27 forks source link

Decode token #34

Closed jokeronaldo closed 6 years ago

jokeronaldo commented 6 years ago

How do I decode a token getting by Auth::getToken()? Is there any other way to get decoded token?

jokeronaldo commented 6 years ago

Already solved creating a helper class. If someone had the same issue, try my class above:

<?php

namespace App\Helpers;

class JwtDecoderHelper
{
    public static function decode($jwt = null)
    {
        $jwt = $jwt ?? \Auth::getToken();

        if ($jwt) {
            $jwt = list($header, $claims, $signature) = explode('.', $jwt);

            $header = self::decodeFragment($header);
            $claims = self::decodeFragment($claims);
            $signature = (string) base64_decode($signature);

            return [
                'header' => $header,
                'claims' => $claims,
                'signature' => $signature
            ];
        }

        return false;
    }

    protected static function decodeFragment($value)
    {
        return (array) json_decode(base64_decode($value));
    }
}

teste.php

<?php

use App\Helpers\JwtDecoderHelper;

$token = 'eAsdasd.QWewrt.asdsa....' // your token as string

var_dump(JwtDecoderHelper::decode($token));

# Get token from this lib when the user is already authenticated, false when unauthenticated
var_dump(JwtDecoderHelper::decode());
DWMcload commented 5 years ago

Working perfectly, so just a thumbs up for you.