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/ */
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);
}
}