Skip to content

3. Logout

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

Note: Revoke & flush data inside the service

Features

  • Revoke token
  • Revoke refresh token

Example

POST /logout
  • Parameters
Request Field Field Type Required Field Desc
Authorization Bearer true access_token for authenticate
  • Responses
Response Field Field Type Required Field Desc
N/A N/A N/A return code 204 - noContent
curl -X 'POST' \
  'http://localhost/api/logout' \
  -H 'accept: application/json' \
  -H 'Authorization: Bearer eyJ0eXAiOiJKV1...' \
  -d ''
{}

Usage

Make route function the following:

# routes/api.php
Route::group([
    'middleware' => 'auth:api',
], function ($router) {
    Route::post('logout', 'AuthController@logout');
});

Make Refresh function the following:

# App\Http\Controllers\AuthController;
public function logout(Request $request)
{
   auth('api')->logout();

   return response()->noContent();
}

Workflow

sequenceDiagram
Controller->>SunGuard: 1. Logout
SunGuard->>SunJWT: 2. Revoke token & access token!
SunJWT-->>SunGuard: 3.a Throw JWT Exception
SunJWT-->>SunGuard: 3.b Successful!
SunGuard-->>Controller: 4. Successful!
Loading

Explain

1. Setting Guard to service provider

# SunAsterisk\Auth\SunServiceProvider
/**
 * Extend Laravel's Auth.
 *
 * @return void
 */
protected function extendAuthGuard(): void
{
    $this->app['auth']->extend('sun', function ($app, $name, array $config) {
        // Create Blacklist instance
        $blackList = new SunBlacklist($app->make(Providers\Storage::class));
        // Create SunJWT instance
        $jwt = new SunJWT($blackList, $app->config->get('sun-asterisk.auth'));
        // Create SunGuard instance
        $guard = new SunGuard(
            $jwt,
            $app['auth']->createUserProvider($config['provider']),
            $app['request']
        );
        app()->refresh('request', $guard, 'setRequest');

        return $guard;
    });
}

2. Create method logout in SunGuard

# SunAsterisk\Auth\SunGuard
/**
 * Logout the user, thus invalidating the token.
 *
 * @return void
 */
public function logout()
{
    try {
        $token = $this->request->bearerToken();
        $this->jwt->invalidate($token);
    } catch (\Exception $e) {
        throw new Exceptions\JWTException($e->getMessage());
    }
}

3. Invalidate token and refreshToken

# SunAsterisk\Auth\SunJWT
public function invalidate(string $token, bool $isRefresh = false): bool
{
    if (! $this->blackList) {
        throw new Exceptions\JWTException('You must have the blacklist enabled to invalidate a token.');
    }

    $payload = $this->decode($token, $isRefresh, false);

    return $this->blackList->add($payload);
}

Clone this wiki locally