PHP code example of albetnov / sanctum-refresh

1. Go to this page and download the library: Download albetnov/sanctum-refresh 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/ */

    

albetnov / sanctum-refresh example snippets


return [
    /**
     * Set the fallback expiration time of both tokens
     * Time in minutes.
     */
    'expiration' => [
        // set the fallback of access token expiration
        'access_token' => 2, // 2 minutes,
        // set the fallback of refresh token expiration
        'refresh_token' => 30, // 30 minutes
    ],
];



namespace App\Http\Controllers;

use Albet\SanctumRefresh\Services\TokenIssuer;

class TokenController {
    function newToken() {
        $token = TokenIssuer::issue($request->user(), guard: 'api');

        return response()->json([
            'message' => 'Token generated successfully!',
            'data' => $token->toArray(),
        ]);
    }
}



// (...)

use Albet\SanctumRefresh\Helpers;
use Albet\SanctumRefresh\Exceptions\SanctumRefreshException;

class TokenMiddleware {
    public function handle(Request $request, \Closure $next): Response {
        
        try {
            Helpers::getRefreshToken(
                $request->get('refresh_token', '') // adjust to your liking, either from Query Parameter, Body, or Header.
            );

            return $next($request);
        } catch (SanctumRefreshException $e) {
            // handle tags of SanctumRefreshException
            return response()->json([
                'error' => 'Refresh token invalid'
            ], 400);
        }
    }
}



// imports...

Route::post('refresh-token', [TokenController::class, 'refreshToken'])->middleware(TokenMiddleware::class);



use Albet\SanctumRefresh\Services\TokenIssuer;

class TokenController {
    public function refreshToken(Request $request) {
        $newToken = TokenIssuer::refreshToken($request->get('refresh-token', ''));

        if(!$newToken) {
            return response()->json([
                'error' => 'Refresh token not valid',
            ], 400);
        }

        return response()->json([
            'message' => 'New token created',
            'data' => $newToken->toArray(),
        ]);
    }
}

Schedule::command('prune:token')->daily();
bash
php artisan vendor:publish --tag="sanctum-refresh-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="sanctum-refresh-config"