Jwt-auth: Get token expiration after JWTAuth::attempt

Created on 26 Nov 2015  路  8Comments  路  Source: tymondesigns/jwt-auth

Hi,

Is there a way to get the expiration time of a recently created token?

Most helpful comment

@tdhsmith is correct, or another way could be

$exp = JWTAuth::setToken('foo.bar.baz')->getPayload()->get('exp');

All 8 comments

If you don't have access to the token itself, no. (Though you could certainly create your own database table to store this information as you create tokens!)

If you _do_ have access to the token:

// v0.5
$payload = JWTAuth::getPayload($token);
$expirationTime = $payload['exp'];

The exp claim is stored as a Unix timestamp.

@tdhsmith is correct, or another way could be

$exp = JWTAuth::setToken('foo.bar.baz')->getPayload()->get('exp');

Hello guys! reading this now I know how to get expiration date thanks, but still I'm a little bit confuse on setting expiration date I don't know exactly how to set it. My idea is set the expiration date for a year since the token was created. I found within the documentation that expiration date can be added within an array of claims, something like this:

$customClaims = ['exp' => 'expDateUnixFormat'];

JWTAuth::attempt($credentials, $customClaims);

And now acording to: [https://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#rfc.section.4.1.4]

_"The processing of the exp claim requires that the current date/time MUST be before the expiration date/time listed in the exp claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL"_

Can you be so kind and help me to unerstand this, please.

The expiration is set based on your configured ttl (in config/jwt.php), which sets the default number of minutes until the token expires. Just change that config value and you'll have tokens with a longer expiration. See the documentation for more info.

You could technically do it the way you were describing, but this way is a lot easier if they're all going to be the same.

Hello tdsmith, thanks for your suggestion. I've set the expiration time:

$expiration_date = Carbon\Carbon::now()->addYear()->timestamp;
$customClaims = ['exp' =>$expiration_date];

    if (! $token = JWTAuth::fromUser($user, $customClaims)) {          
      return response()->json(['Message:' => trans('signup.invalid_credentials')], 401);
    }       

But now I have a couple more doubts and concerns within login and log out. I'm still figuring out how it works I'm reading JWAth class to find out how login an log out works also which methods should I use. Is there an example when a user attemps to log in once that he has created his account. And another example when user logs out??

Thanks!

Base64.Decoder decoder = Base64.getUrlDecoder();
String src = " ";//pass token string here;
String[] parts = src.split("\."); // Splitting header, payload and signature
System.out.println("Headers: "+new String(decoder.decode(parts[0]))); // Header
System.out.println("Payload: "+new String(decoder.decode(parts[1]))); // Payload

The payload of the expired cookie is required to set the lifetime of the cookie for refresh token. But it's not possible on 1.0 version.

The payload of the expired cookie is required to set the lifetime of the cookie for refresh token. But it's not possible on 1.0 version.

This appears to be what I'm seeing now. In my config/jwt.php file, I have:

'ttl' => env('JWT_TTL', 1),

But $this->guard()->getPayload()->get('exp') - time() returns 60, so it doesn't appear to be respecting the config setting. I also put JWT_TTL=1 in my .env file and ->get('exp') still returns 60.

I have a work-around though. Now I am doing this to pass the config expiry to the SPA client:

spa.blade.php (root layout file)

@php
$config = [
    'appName' => config('app.name'),
    'github' => [
        'client_id' => config('services.github.client_id'),
        'callback_url' => config('services.github.callback_url'),
        'provider_name' => config('services.github.provider_name'),
    ],
    'twitter' => [
        'client_id' => config('services.twitter.client_id'),
        'callback_url' => config('services.twitter.callback_url'),
        'provider_name' => config('services.twitter.provider_name'),
    ],
    'jwt' => [
        'ttl' => config('jwt.ttl'),
        'refresh_ttl' => config('jwt.refresh_ttl'),
    ],
];
@endphp

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head> ... </head>

    <body>
        <div id="app"> ... </div>

        <script>
            'use strict';
            window.config = @json($config);
        </script>

    </body>
</html>

Then, I can pick up those variables on the JavaScript side:

some-component.vue

export default {
    methods: {
        handleSomething() {
            console.log('config', window.config.jwt);
        },
    },
};

or

this.$store.dispatch('auth/saveToken', {
    token,
    expires_in: window.config.jwt.ttl,
});

I'm noticing now, when JWT_TTL=1 is declared in the .env file, it shows up as string in JavaScript. You can fix that by typecasting:

@php
$config = [
    'jwt' => [
        'ttl' => (int)config('jwt.ttl'),
        'refresh_ttl' => (int)config('jwt.refresh_ttl'),
    ],
];
@endphp

Also don't forget about the unary operator in JavaScript:

// JS TRIVIA BONUS: unary is more performant (by negligible amounts) than `Number()`
// because it omits one `if` condition in the compiler
+window.config.jwt.ttl
Was this page helpful?
0 / 5 - 0 ratings

Related issues

phamduong picture phamduong  路  3Comments

agneshoving picture agneshoving  路  3Comments

aofdev picture aofdev  路  3Comments

therealmjk picture therealmjk  路  3Comments

lloy0076 picture lloy0076  路  3Comments