PHP code example of malvik-lab / laravel-jwt

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

    

malvik-lab / laravel-jwt example snippets



## config/auth.php

return [
    // ...

    'guards' => [
        // ...
        
        'jwt-access-token' => [
            'driver' => 'jwt-access-token',
            'provider' => 'users',
        ],
    
        'jwt-refresh-token' => [
            'driver' => 'jwt-refresh-token',
            'provider' => 'users',
        ]
    ],

    // ...
];


## app/Providers/AuthServiceProvider.php

namespace App\Providers;

// ...
use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Foundation\Application;
use MalvikLab\LaravelJwt\Http\Guards\JwtAccessTokenGuard;
use MalvikLab\LaravelJwt\Http\Guards\JwtRefreshTokenGuard;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        // ...
    ];

    public function boot(): void
    {
        // ...
    
        Auth::extend('jwt-access-token', function (Application $app, string $name, array $config) {
            return new JwtAccessTokenGuard(Auth::createUserProvider($config['provider']));
        });

        Auth::extend('jwt-refresh-token', function (Application $app, string $name, array $config) {
            return new JwtRefreshTokenGuard(Auth::createUserProvider($config['provider']));
        });
    }
}


## app/routes/api.php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use MalvikLab\LaravelJwt\Http\Controllers\AuthController;

Route::middleware(['guest'])->group(function () {
    Route::post('/auth/login', [AuthController::class, 'login']);
});

Route::middleware(['auth:jwt-access-token'])->group(function () {
    Route::post('/auth/logout', [AuthController::class, 'logout']);
    Route::get('/auth/me', [AuthController::class, 'me']);
});

Route::middleware(['auth:jwt-refresh-token'])->group(function () {
    Route::post('/auth/refresh', [AuthController::class, 'refresh']);
});



namespace App\Http\Controllers;

use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use MalvikLab\LaravelJwt\Services\AuthService\AuthService;
use MalvikLab\LaravelJwt\Services\JwtService\TokenOptions;

class AuthController extends Controller
{
    private AuthService $authService;
    private Guard $accessTokenGuard;

    public function __construct()
    {
        $this->authService = new AuthService();
        $this->accessTokenGuard = Auth::guard('jwt-access-token');
    }

    public function login(Request $request): JsonResponse
    {
        // Validate the request and retrieve the user
        // or use the Auth Service method
        $user = $this->authService->checkCredentials($request->all());

        $options = new TokenOptions();
        $options->setRole('mod');
        $options->setPermissions([
            'add-post',
            'edit-post',
            'delete-post'
        ]);
        $options->setAccessTokenTtl(14400);
        $options->setRefreshTokenTtl(2592000);

        $this->accessTokenGuard->login($user, $options);

        return $this->accessTokenGuard->response();
    }
    
    public function me(Request $request): JsonResponse
    {
        $authToken = $this->accessTokenGuard->getAuthToken();

        $this->accessTokenGuard->hasRole('mod');
        $this->accessTokenGuard->hasRoles(['mod', 'other-role']);
        $this->accessTokenGuard->hasPermission('add-post');
        $this->accessTokenGuard->hasPermissions(['add-post', 'edit-post', 'delete-post']);

        return response()->json($request->user());
    }
}


## app/Exceptions/Handler.php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Response;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use Throwable;

class Handler extends ExceptionHandler
{
    protected $dontFlash = [
        // ...
    ];

    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, Throwable $e): Response | JsonResponse | RedirectResponse |SymfonyResponse
    {
        if ( $request->is('api/*') )
        {
            $request->headers->set('accept', 'application/json');
        }

        return parent::render($request, $e);
    }
}


## app/Http/Kernel.php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    protected $middleware = [
        // ...
    ];

    protected $middlewareGroups = [
        'web' => [
            // ...
        ],

        'api' => [
            \MalvikLab\LaravelJwt\Http\Middleware\AcceptJson::class,
            // ...
        ],
    ];

    // ...
}

sh
php artisan vendor:publish --tag=jwt-config
sh
php artisan vendor:publish --tag=jwt-migration
sh
php artisan migrate
sh
php artisan jwt:keys