PHP code example of pivotphp / security

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

    

pivotphp / security example snippets


use PivotPHP\Security\Cors\CorsConfig;
use PivotPHP\Security\Cors\CorsMiddleware;

$cors = new CorsMiddleware($responseFactory, new CorsConfig(
    allowedOrigins: ['https://app.example.com'],
    allowCredentials: true,
));

use PivotPHP\Security\Proxy\TrustedProxyConfig;
use PivotPHP\Security\Proxy\TrustedProxyMiddleware;

$proxy = new TrustedProxyMiddleware(new TrustedProxyConfig(
    trustedProxies: ['10.0.0.0/8', '2001:db8::/32'],
));

// later: $request->getAttribute('client_ip')

use PivotPHP\Security\Headers\SecurityHeadersConfig;
use PivotPHP\Security\Headers\SecurityHeadersMiddleware;

$headers = new SecurityHeadersMiddleware(); // API defaults

new SecurityHeadersConfig(contentSecurityPolicy: [
    'default-src' => ['self' => true],
    'img-src' => ['allow' => ['https://cdn.example.com']],
]);

use PivotPHP\Security\Csrf\CsrfMiddleware;
use Yiisoft\Csrf\Hmac\HmacCsrfToken;
use Yiisoft\Csrf\MaskedCsrfToken;

$token = new MaskedCsrfToken(new HmacCsrfToken($identityGenerator, $secret, 'sha256', 3600));
$csrf = new CsrfMiddleware($responseFactory, $token);

// render: $request->getAttribute('csrf_token')->getValue()

use PivotPHP\Security\Jwt\JwtAuthMiddleware;
use PivotPHP\Security\Jwt\JwtConfig;

$auth = new JwtAuthMiddleware($responseFactory, new JwtConfig(
    key: $_ENV['JWT_SECRET'],          // ≥ 32 bytes for HS256
    algorithm: 'HS256',
    publicPaths: ['/health', '/docs/*'],
));

// in the handler: $request->getAttribute('user') — the claims as an array

use PivotPHP\Security\Jwt\JwtIssuer;

$issuer = new JwtIssuer($config);                     // HS*: signs with the configured secret
// $issuer = new JwtIssuer($config, $privateKeyPem);  // RS*/PS256/ES*/EdDSA: private key 

use PivotPHP\Security\RateLimit\RateLimitConfig;
use PivotPHP\Security\RateLimit\RateLimitMiddleware;
use Symfony\Component\RateLimiter\RateLimiterFactory;

$limiter = new RateLimiterFactory(
    ['id' => 'login', 'policy' => 'sliding_window', 'limit' => 5, 'interval' => '1 minute'],
    $storage,      // e.g. CacheStorage over Redis
    $lockFactory,  // symfony/lock —