PHP code example of huseynvsal / jwt-auth-refresh

1. Go to this page and download the library: Download huseynvsal/jwt-auth-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/ */

    

huseynvsal / jwt-auth-refresh example snippets


// config/auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users'
    ],

    'api' => [
        'driver' => 'jwt',
        'provider' => 'users'
    ]
]

// app/Models/User.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Huseynvsal\JwtAuthRefresh\Models\AccessToken;
use Huseynvsal\JwtAuthRefresh\Models\RefreshToken;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    public function refreshTokens(): HasMany
    {
        return $this->hasMany(RefreshToken::class, 'user_id');
    }

    // Additional user logic...
}

// app/Http/Controllers/AuthController.php

namespace App\Http\Controllers;

use App\Models\Customer;
use Huseynvsal\JwtAuthRefresh\Exceptions\InvalidTokenException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Huseynvsal\JwtAuthRefresh\Services\JwtAuthService;

class AuthController extends Controller
{
    protected JwtAuthService $jwtAuthService;

    public function __construct(JwtAuthService $jwtAuthService)
    {
        $this->jwtAuthService = $jwtAuthService;
    }

    public function login(): JsonResponse
    {
        $user = User::find(1);

        $accessToken = $this->jwtAuthService->generateAccessToken($user);
        $refreshToken = $this->jwtAuthService->generateRefreshToken($user);

        return response()->json([
            'accessToken' => $accessToken,
            'refreshToken' => $refreshToken
        ]);
    }
}

// app/Http/Controllers/AuthController.php

public function refresh(Request $request): JsonResponse
{
    try
    {
        $tokens = $this->jwtAuthService->refreshTokens($request->input('refreshToken'));

        return response()->json($tokens);
    }
    catch (InvalidTokenException $e)
    {
        return response()->json(['error' => $e->getMessage()], 401);
    }
}

// app/Http/Controllers/AuthController.php

public function logout(): JsonResponse
{
    $user = auth()->user();
    $this->jwtAuthService->revokeTokensForUser($user);

    return response()->json(['message' => 'Logged out successfully']);
}
bash
php artisan vendor:publish --tag=jwt-auth-config
php artisan vendor:publish --tag=jwt-auth-migrations
bash
php artisan migrate