PHP code example of yiisoft / csrf

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

    

yiisoft / csrf example snippets


$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class);
$middlewareDispatcher = $middlewareDispatcher->withMiddlewares([
    ErrorCatcher::class,
    SessionMiddleware::class,
    CsrfTokenMiddleware::class, // <-- add this
    Router::class,
]);

// config/web/di/application.php
return [
    MiddlewareDispatcher::class => [
        'withMiddlewares()' => [[
            ErrorCatcher::class,
            SessionMiddleware::class,
            CsrfTokenMiddleware::class, // <-- add this
            Router::class,
        ]]
    ],
];

/** @var Yiisoft\Csrf\CsrfTokenInterface $csrfToken */
$csrf = $csrfToken->getValue();

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Yiisoft\Csrf\CsrfTokenMiddleware;

/**
 * @var Psr\Http\Message\ResponseFactoryInterface $responseFactory
 * @var Yiisoft\Csrf\CsrfTokenInterface $csrfToken
 */
 
$failureHandler = new class ($responseFactory) implements RequestHandlerInterface {
    private ResponseFactoryInterface $responseFactory;
    
    public function __construct(ResponseFactoryInterface $responseFactory)
    {
        $this->responseFactory = $responseFactory;
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $response = $this->responseFactory->createResponse(400);
        $response
            ->getBody()
            ->write('Bad request.');
        return $response;
    }
};

$middleware = new CsrfTokenMiddleware($responseFactory, $csrfToken, $failureHandler);

use Yiisoft\Csrf\CsrfTokenMiddleware;
use Yiisoft\Http\Method;

$csrfTokenMiddleware = $container->get(CsrfTokenMiddleware::class);

// Returns a new instance with the specified list of safe methods.
$csrfTokenMiddleware = $csrfTokenMiddleware->withSafeMethods([Method::OPTIONS]);

// Returns a new instance with the specified header name.
$csrfTokenMiddleware = $csrfTokenMiddleware->withHeaderName('X-CSRF-PROTECTION');

// config/web/di/csrf-token.php
use Yiisoft\Csrf\CsrfTokenMiddleware;
use Yiisoft\Http\Method;

return [
    CsrfTokenMiddleware::class => [
        'withSafeMethods()' => [[Method::OPTIONS]],
        'withHeaderName()' => ['X-CSRF-PROTECTION'],
    ],
];

$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class);
$middlewareDispatcher = $middlewareDispatcher->withMiddlewares([
    ErrorCatcher::class,
    CsrfHeaderMiddleware::class, // <-- add this
    Router::class,
]);

// config/web/di/application.php
return [
    MiddlewareDispatcher::class => [
        'withMiddlewares()' => [[
            ErrorCatcher::class,
            CsrfHeaderMiddleware::class, // <-- add this
            Router::class,
        ]]
    ],
];

// config/web/di/router.php
return [
    RouteCollectionInterface::class => static function (RouteCollectorInterface $collector) use ($config) {
        $collector
            ->middleware(CsrfHeaderMiddleware::class) // <-- add this
            ->addGroup(Group::create(null)->routes($routes));

        return new RouteCollection($collector);
    },
];

use Yiisoft\Csrf\CsrfHeaderMiddleware;
use Yiisoft\Http\Method;

$csrfHeaderMiddleware = $container->get(CsrfHeaderMiddleware::class);

// Returns a new instance with the specified list of unsafe methods.
$csrfHeaderMiddleware = $csrfHeaderMiddleware->withUnsafeMethods([Method::POST]);

// Returns a new instance with the specified header name.
$csrfHeaderMiddleware = $csrfHeaderMiddleware->withHeaderName('X-CSRF-PROTECTION');

// config/web/di/csrf-header.php
use Yiisoft\Csrf\CsrfHeaderMiddleware;
use Yiisoft\Http\Method;

return [
    CsrfHeaderMiddleware::class => [
        'withUnsafeMethods()' => [[Method::POST]],
        'withHeaderName()' => ['X-CSRF-PROTECTION'],
    ],
];

$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class);
$middlewareDispatcher = $middlewareDispatcher->withMiddlewares([
    ErrorCatcher::class,
    CsrfHeaderMiddleware::class, // <-- add this
    Router::class,
]);

$collector = $container->get(RouteCollectorInterface::class);
$collector->addGroup(
    Group::create('/api')
        ->middleware(CsrfHeaderMiddleware::class) // <-- add this
        ->routes($routes)
);

$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class);
$middlewareDispatcher = $middlewareDispatcher->withMiddlewares([
    ErrorCatcher::class,
    CsrfHeaderMiddleware::class, // <-- add this
    Router::class,
]);

$collector = $container->get(RouteCollectorInterface::class);
$collector->addGroup(
    Group::create('/api')
        ->middleware(CsrfHeaderMiddleware::class) // <-- add this
        ->routes($routes)
);

use Yiisoft\Csrf\CsrfTokenMiddleware;
use Yiisoft\Http\Method;

$csrfTokenMiddleware = $container->get(CsrfTokenMiddleware::class);
$csrfTokenMiddleware = $csrfTokenMiddleware->withSafeMethods([Method::OPTIONS]);

// config/web/di/csrf-token.php
use Yiisoft\Csrf\CsrfTokenMiddleware;
use Yiisoft\Http\Method;

return [
    CsrfTokenMiddleware::class => [
        'withSafeMethods()' => [[Method::OPTIONS]],
    ],
];

$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class);
$middlewareDispatcher = $middlewareDispatcher->withMiddlewares([
    ErrorCatcher::class,
    SessionMiddleware::class,
    CsrfTokenMiddleware::class, // <-- add this
    Router::class,
]);

$collector = $container->get(RouteCollectorInterface::class);
$collector->addGroup(
    Group::create('/api')
        ->middleware(CsrfTokenMiddleware::class) // <-- add this
        ->routes($routes)
);

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Yiisoft\Http\Header;
use Yiisoft\Http\Method;
use Yiisoft\Router\Route;

Route::options('/csrf-token')
    ->action(static function (
        ResponseFactoryInterface $responseFactory,
        CsrfTokenInterface $token
    ): ResponseInterface {
        $tokenValue = $token->getValue();

        $response = $responseFactory->createResponse()
            ->withHeader(Header::ALLOW, Method::OPTIONS)
            ->withHeader('X-CSRF-TOKEN', $tokenValue);

        $response->getBody()->write($tokenValue);

        return $response;
    }),