How to edit laravel passport token's expires_at field

对着背影说爱祢 提交于 2019-12-23 02:54:14

问题


I am trying to edit expires_at field of my token with a middleware like bellow

namespace App\Http\Middleware;

use Carbon\Carbon;
use Closure;
use Auth;

class Refresh
{

    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = Auth::user()->token();
        $expiresDate = $token->expires_at;
        $currentDate = Carbon::now();
        $diff = date_diff_in_minutes($currentDate, $expiresDate);
        $baseExpire = site_config('token_expires_minutes');
        if ($diff > 0 && $diff < $baseExpire) {
            $token->update([
                'expires_at' => (new Carbon($expiresDate))->addMinutes(intval($baseExpire - $diff))
            ]);
        }

        return $next($request);
    }
}

Updating token's expires_at field in each api requests works fine.

But the token expires at the first expires_at date.

I know there is a refresh_token method that i can use for this but i have some issues with refresh tokens and because of that i have to increase token's life time without revoking.

Do you know why this happening? How can i fix this?


回答1:


According to the docs, the default token lifetime should be set in your AuthServiceProvider.php by calling the Passport::tokensExpireIn() function in your boot() method.

Example:

public function boot() {
    ...

    $baseExpire = site_config('token_expires_minutes');

    Passport::tokensExpireIn(now()->addMinutes($baseExpire));
}

EDIT

Sorry, I misunderstood your original question. Unfortunately, it's not possible to change the expiration of a generated token, since the expiration is encoded into the actual token string (Laravel uses https://github.com/lcobucci/jwt to generate and validate tokens). However, you may look into overriding the passport validation to check the expiration on the table rather than using the default package.



来源:https://stackoverflow.com/questions/51801351/how-to-edit-laravel-passport-tokens-expires-at-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!