1. Go to this page and download the library: Download cube43/slim-jwt-auth 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/ */
cube43 / slim-jwt-auth example snippets
use Slim\Factory\AppFactory;
use Tuupola\Middleware\JwtAuthentication;
use Tuupola\Middleware\JwtAuthenticationOption;
use Tuupola\Middleware\JwtAuthentificationFirewall;
use Tuupola\Middleware\JwtAuthentication\FetchTokenFormHeader;
use Tuupola\Middleware\JwtAuthentication\RequestPathRule;
use Tuupola\Middleware\JwtAuthentificationUnAuthorizedHandler;
use Tuupola\Middleware\JwtAuthentificationBeforeHandler;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Token\Plain;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Laminas\Diactoros\Response;
use Throwable;
$app = AppFactory::create();
// 1. Configure Options
$options = JwtAuthenticationOption::create(InMemory::plainText('super-secret-key'))
->withTokenAttributeName('jwt')
->withAllowedInsecureHosts(['localhost', '127.0.0.1'])
->withBeforeHandleRequestWhenTokenAvailable(new class implements JwtAuthentificationBeforeHandler {
public function __invoke(ServerRequestInterface $request, Plain $token): ServerRequestInterface
{
assert($request->getAttribute('jwt') === $token);
return $request->withAttribute('user_uuid', $token->claims()->get('uuid'));
}
});
// 2. Define Rules (e.g. protect /api, but allow /api/login)
$pathRule = new RequestPathRule(
path: ['/api'],
ignore: ['/api/login', '/api/token']
);
// 3. Define Unauthorized Handler (JSON response)
$unauthorizedHandler = new class implements JwtAuthentificationUnAuthorizedHandler {
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Throwable $exception): ResponseInterface
{
$response->getBody()->write(json_encode(['status' => 'error', 'message' => 'Unauthorized']));
return $response->withHeader('Content-Type', 'application/json');
}
};
// 4. Add Middleware (LIFO: Add Firewall first, then Authentication)
// Firewall: Checks rules and blocks if no token is present when
$options = JwtAuthenticationOption::create(InMemory::plainText('secret'))
->withTokenAttributeName('jwt') // Attribute name for the decoded token
->withEnforceHttps(true) // Require HTTPS
->withAllowedInsecureHosts(['localhost']); // Allow HTTP on these hosts
use Tuupola\Middleware\JwtAuthentication\FetchTokenFormHeader;
use Tuupola\Middleware\JwtAuthentication\FetchTokenFormCookie;
$app->add(JwtAuthentication::create(
$options,
new FetchTokenFormHeader('Authorization', '/Bearer\s+(.*)$/i'),
new FetchTokenFormCookie('auth_token')
));
use Tuupola\Middleware\JwtAuthentication\RequestPathRule;
// Authenticate everything under /api, but ignore /api/login
$pathRule = new RequestPathRule(
path: ['/api'],
ignore: ['/api/login']
);
$app->add(new JwtAuthentificationFirewall(
$options,
$response,
new NullUnAuthorizedHandler(), // Default handler
$pathRule
));
use Tuupola\Middleware\JwtAuthentication\IgnoreHttpMethodRule;
$methodRule = new IgnoreHttpMethodRule(['OPTIONS']);
$app->add(new JwtAuthentificationFirewall(
$options,
$response,
new NullUnAuthorizedHandler(),
$pathRule,
$methodRule
));
use Tuupola\Middleware\JwtAuthentificationBeforeHandler;
use Lcobucci\JWT\Token\Plain;
$options = $options->withBeforeHandleRequestWhenTokenAvailable(new class implements JwtAuthentificationBeforeHandler {
public function __invoke(ServerRequestInterface $request, Plain $token): ServerRequestInterface
{
assert($request->getAttribute('jwt') === $token);
return $request->withAttribute('user_id', $token->claims()->get('uid'));
}
});
use Tuupola\Middleware\JwtAuthentificationAfterHandler;
$options = $options->withAfterHandleRequestWhenTokenAvailable(new class implements JwtAuthentificationAfterHandler {
public function __invoke(ResponseInterface $response, Plain $token): ResponseInterface
{
return $response->withHeader('X-Auth-Success', 'true');
}
});
use Tuupola\Middleware\JwtAuthentificationUnAuthorizedHandler;
$firewall = new JwtAuthentificationFirewall(
$options,
$response,
new class implements JwtAuthentificationUnAuthorizedHandler {
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Throwable $exception): ResponseInterface
{
$response->getBody()->write(json_encode(['error' => 'Unauthorized']));
return $response->withHeader('Content-Type', 'application/json');
}
}
);