PHP code example of kuick / security

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

    

kuick / security example snippets


use Kuick\Http\HttpException;
use Kuick\Http\Message\Response;
use Psr\Http\Message\ServerRequestInterface;

class BearerTokenGuard
{
    public function __invoke(ServerRequestInterface $request): void
    {
        $authHeader = $request->getHeaderLine('Authorization');
        if (!str_starts_with($authHeader, 'Bearer valid-token')) {
            throw new HttpException(Response::HTTP_UNAUTHORIZED, 'Invalid or missing token');
        }
    }
}

use Kuick\Security\Guardhouse;
use Psr\Log\NullLogger;

$guardhouse = (new Guardhouse(new NullLogger()))
    // protect all routes with a token check
    ->addGuard('/api/.*', new BearerTokenGuard())
    // restrict a specific route to GET only
    ->addGuard('/api/resource/(?P<id>\d+)', new BearerTokenGuard(), ['GET']);

use Kuick\Security\SecurityMiddleware;

$middleware = new SecurityMiddleware($guardhouse, new NullLogger());

// Example with any PSR-15-compatible dispatcher (e.g. Relay, Slim, etc.)
$response = $middleware->process($serverRequest, $nextHandler);

// Guard registered for: '/users/(?<userId>\d+)'
// Request: GET /users/42
// Inside the guard, $request->getQueryParams()['userId'] === '42'