Skip to content

6. Refresh token

dungda-0794 edited this page Feb 7, 2023 · 7 revisions

Refresh token use service from package.

Note: Generate refresh token & secret token inside the service

Make Refresh function the following:

# App\Http\Controllers\AuthController;
public function refresh(Request $request)
{
    $token = $request->refresh_token;

    $rs = $this->service->refresh($token);

    return response()->json($rs);
}

Flow refresh inside service package as follows:

1. Decode refresh token

# SunAsterisk\Auth\Contracts\AuthJwtService;
public function refresh(?string $refreshToken, callable $callback = null): array
{
    ...
    $payload = $this->jwt->decode($refreshToken ?: '', true);
}

2. Compare exp time of the refresh token

# SunAsterisk\Auth\Contracts\AuthJwtService;
public function refresh(?string $refreshToken, callable $callback = null): array
{
    ...
    if (Carbon::createFromTimestamp($payload['exp'])->lte(Carbon::now())) {
        throw new InvalidArgumentException('The RefreshToken is invalid.');
    }
}

3. Verify user exists

# SunAsterisk\Auth\Contracts\AuthJwtService;
public function refresh(?string $refreshToken, callable $callback = null): array
{
    ...
    $item = $this->repository->findById($sub?->id);
    if (!$item) {
        throw new InvalidArgumentException('The RefreshToken is invalid.');
    }
}

4. Revoke all access token

# SunAsterisk\Auth\Contracts\AuthJwtService;

5. Re generate access token

# SunAsterisk\Auth\Contracts\AuthJwtService;
public function refresh(?string $refreshToken, callable $callback = null): array
{
    ...
    $payload = $this->jwt->make((array) $sub)->toArray();
    $payloadRefresh = $this->jwt->make((array) $sub, true)->toArray();

    $jwt = $this->jwt->encode($payload);
    $refresh = $this->jwt->encode($payloadRefresh, true);
}

Method refresh will return an array

# SunAsterisk\Auth\Contracts\AuthJwtService;
public function refresh(?string $refreshToken, callable $callback = null): array
{
    ...
    return [
        'refresh_token' => 'eyJhbGciOiJIUzI1NiIsIn...',
        'access_token' => 'eyJiwibmFtZSI6Ikpva...',
        'token_type' => 'bearer',
        'expires_at' => 1675742447,
    ];
}

Sun_ Auth _ Architecture Design-Refresh token

Clone this wiki locally