user254153
user254153

Reputation: 1883

Set expiry time for laravel jwt dynamically

Hi I am using angular js in front end with satellizer and laravel at backend with tymon jwt library. I am using jwt authentication. I want to make remember me functionalities in my web app. I see 'ttl' to set expiry time of token in laravel 'config/jwt.php.

 /*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour
|
*/

'ttl' => 60,

By default, it will be 1 hour. But I want to change this dynamically to 1 week if user clicks remember me while login. How can I change it dynamically. Thank you.

Upvotes: 22

Views: 90075

Answers (12)

Danilo Santos
Danilo Santos

Reputation: 452

can you do that

$token = auth('api')->setTTL((AuthController::EXPIRE_IN_DAYS * AuthController::MINUTES_IN_DAY))->attempt($credentials);

get data payload

$data = JWTAuth::decode(new Token( $token))->toArray();
{
  "iss": "",
  "iat": ,
  "exp": ,
  "nbf": ,
  "jti": "",
  "sub": ,
  "prv": ""
}
response("Success",'LOGIN_SUCCESS',[
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $data['exp']
        ]);

Upvotes: 0

ashutosh singh
ashutosh singh

Reputation: 11

Override the token ttl without any changing in config/jwt.php

$token = auth()->setTTL(7200)->attempt($credentials);

Upvotes: 1

Andrii Lutskevych
Andrii Lutskevych

Reputation: 1379

You can use JWTFactory (1.0 version)

$myTTL = 30; //minutes

JWTAuth::factory()->setTTL($myTTL);
$token = JWTAuth::attempt($credentials);

Upvotes: 12

Nilanth
Nilanth

Reputation: 39

You can set the token expiration dynamically by using

JWTAuth::factory()->setTTL($expirationInMinutes);

JWTAuth::attempt($credentials)

Below code will not work in the latest version

$token = JWTAuth::attempt($credentials, ['exp' => Carbon\Carbon::now()->addDays(7)->timestamp]);

Upvotes: 0

Mahmoud Kassem
Mahmoud Kassem

Reputation: 429

Tymon JWT v 1.0

you can override default ttl when attempting to login user:

if (! $token = auth()->setTTL(1)->attempt($credentials)) {
  return response()->json(['message' => 'Unauthorized user'], 401);
}

Upvotes: 1

Expert Suggestion
Expert Suggestion

Reputation: 401

Increase Laravel auth token expire time

SESSION_LIFETIME=10080

Default value 120 min in session.php

Upvotes: -1

joel
joel

Reputation: 181

None of the above answers worked for me. I managed to get it working like this.

$ttl_in_minutes = 60*24*100;
// The parameter passed to the auth helper should match what is present in config/auth.php
if($request->input('remember')) auth('api')->factory()->setTTL($ttl_in_minutes);

Upvotes: 1

Sulung Nugroho
Sulung Nugroho

Reputation: 1683

For JWT version 1.0.0-rc.2 it's very clear described on the documentation on config/jwt.php

As per note : .... You can also set this to null, to yield a never expiring token. Some people may want this behaviour for e.g. a mobile app. This is not particularly recommended, so make sure you have appropriate systems in place to revoke the token if necessary. Notice: If you set this to null you should remove 'exp' element from 'required_claims' list.

'ttl' => env('JWT_TTL', 60)  meaning we must set 60 to null

 'required_claims' => [
        'iss',
        'iat',
       // 'exp',  <- remove this
        'nbf',
        'sub',
        'jti',
    ],

Upvotes: 0

Vedmant
Vedmant

Reputation: 2581

You can do following to generate JWT token with needed expire time:

JWTAuth::customClaims(['exp' => Carbon\Carbon::now()->addDays(2)->timestamp])
    ->fromUser($user);

Upvotes: 8

Jamesking56
Jamesking56

Reputation: 3901

You can add exp as a custom claim as follows:

$token = JWTAuth::attempt($credentials, ['exp' => Carbon\Carbon::now()->addDays(7)->timestamp]);

The code above creates a token that expires in 7 days time. You don't have to use Carbon it just requires a Unix timestamp, I've used Carbon here for simplicity since its built into Laravel.

Upvotes: 16

Yoram de Langen
Yoram de Langen

Reputation: 5499

I'm not 100% sure, but what happens if you set within your AppServiceProvider@register the config:

config()->set('jwt.ttl', 60*60*7);

or with a facade:

Config::set('jwt.ttl', 60*60*7);

Why would you set it dynamically? Or do you not use the publishing from the config (it's not publishing the config/jwt.php)?

EDIT:

Another solution would be to set it through your .env file:

config/jwt.php
// set the default TTL to one week if the .env file does not contain a `JWT_TTL` var
'ttl' => env('JWT_TTL', 60*60*7), 

And within .env:

JWT_TTL=3600

Upvotes: 6

Prakash P
Prakash P

Reputation: 340

We can set token expiry time while creating the JWT token . It can be set in the token parameter. For example

$token      = array(
                         "iss" => "http://example.com",
                          "aud" => "http://example.com",
                          "exp" => {YOUR_EXPIRY_TIME}
                        );
$jwt=new JWT();
$JWT_TOKEN=$jwt->encode($token, {YOUR_KEY});

The new token will be generated with the corresponding expiry time.

Upvotes: 0

Related Questions