PHP code example of d076 / sanctum-refresh-tokens

1. Go to this page and download the library: Download d076/sanctum-refresh-tokens library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

d076 / sanctum-refresh-tokens example snippets


use D076\SanctumRefreshTokens\Models\AuthenticatableUser;

class User extends AuthenticatableUser
{
    // ...
}

use D076\SanctumRefreshTokens\HasApiTokensInterface;
use D076\SanctumRefreshTokens\Traits\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements HasApiTokensInterface
{
    use HasApiTokens;
}

// config/sanctum.php
'expiration' => env('SANCTUM_ACCESS_TOKEN_EXPIRATION', 60),                          // access token, minutes
'refresh_token_expiration' => env('SANCTUM_REFRESH_TOKEN_EXPIRATION', 43200),        // refresh "remember me", minutes (30 days)
'refresh_token_expiration_no_remember' => env('SANCTUM_REFRESH_TOKEN_EXPIRATION_NO_REMEMBER', 1440), // refresh without remember, minutes (1 day)

use D076\SanctumRefreshTokens\Services\TokenService;

$tokens = (new TokenService($user))->createTokens();

$tokens = (new TokenService($user))->createTokens(
    accessTokenExpiresAt: now()->addMinutes(15),
    refreshTokenExpiresAt: now()->addDays(7),
    abilities: ['orders:read', 'orders:write'],
);

$tokens->access_token;              // plain-text bearer token
$tokens->refresh_token;             // plain-text refresh token ("{id}|{token}")
$tokens->token_type;                // "Bearer"
$tokens->access_token_expires_at;   // Carbon|null
$tokens->refresh_token_expires_at;  // Carbon|null
$tokens->model;                     // morph class of the user
$tokens->user;                      // the user model

return response()->json($tokens);   // implements Arrayable

use D076\SanctumRefreshTokens\DTOs\LoginDTO;
use D076\SanctumRefreshTokens\Services\IAuthService;

public function login(Request $request, IAuthService $auth)
{
    $credentials = new LoginDTO(
        email: $request->input('email'),
        password: $request->input('password'),
        model: User::class,
        remember: $request->boolean('remember'),
    );

    // throws Illuminate\Auth\AuthenticationException on bad credentials
    $tokens = $auth->setCredentials($credentials)->login();

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

$tokens = $auth->setUser($user)->login();

public function refresh(Request $request, IAuthService $auth)
{
    // throws AuthenticationException if the token is unknown, expired or already used
    $tokens = $auth->refresh($request->input('refresh_token'));

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

public function logout(Request $request, IAuthService $auth)
{
    $auth->setUser($request->user())->logout();

    return response()->noContent();
}

$auth->setUser($user)->resetPassword($newPassword);

use D076\SanctumRefreshTokens\Services\TokenService;

(new TokenService($user))->deleteCurrentTokens(); // current pair only
(new TokenService($user))->deleteAllTokens();      // every pair

use Illuminate\Support\Facades\Schedule;

Schedule::command('sanctum:prune-expired --hours=0')->hourly();
Schedule::command('sanctum:prune-refresh-expired --hours=0')->daily();

class User extends AuthenticatableUser
{
    public function getEmailField(): string
    {
        return 'login';
    }

    public function getPasswordField(): string
    {
        return 'pass_hash';
    }
}

use D076\SanctumRefreshTokens\Services\IAuthService;
use D076\SanctumRefreshTokens\Services\ITokenService;

$this->app->bind(IAuthService::class, MyAuthService::class);
$this->app->bind(ITokenService::class, MyTokenService::class);
bash
php artisan vendor:publish --tag=sanctum-refresh-tokens
php artisan migrate
bash
php artisan vendor:publish --tag=sanctum-refresh-tokens
php artisan migrate
bash
php artisan sanctum:prune-refresh-expired --hours=0