Search code examples
laravelaccess-tokenrestful-authenticationlaravel-passport

How to change expiration date of access token Laravel Passport


I'm trying to change the expiration date of access token Laravel Passport.

Here's what I have tried:

AuthServiceProvider

public function boot(){
    $this->registerPolicies();

    Passport::routes();

    Passport::tokensExpireIn(Carbon::now()->addDays(1));
    Passport::refreshTokensExpireIn(Carbon::now()->addDays(2));
    Passport::personalAccessTokensExpireIn(Carbon::now()->addMonths(1));
}

UserController

public function login() {
    $credentials = [
        'email' => request('email'),
        'password' => request('password')
    ];
    if (Auth::attempt($credentials)) {
        $success['token'] = Auth::user()->createToken('MyApp')->accessToken;
        $success['name'] = Auth::user()->name;

        return response()->json(['success' => $success]);
    }
    return response()->json(['error' => 'Unauthorized'], 401);
}

But it didn't work. The expired date didn't change in the database at field expires_at, it's still one year by default.

I'm trying to do this, cause I want to make a redirect to login form when access token will get expired. How can I do it?

I'm also not sure what would happen with a refresh token, will it return another access token and the user will not need to authorizе?


Solution

  • You're creating a personal access token that belongs to user.

    A personal access token has a default expiration date of 1 year.

    Looking at your code I'm pretty sure that this command should do the work:

    Passport::personalAccessTokensExpireIn(Carbon::now()->addMonths(1));
    

    Double-check the expire_at column in the database and expires_in value in your response when you getting the token. It shows the number of seconds the token lives.