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;
}
$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();
}
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);