Secure your API with CORS

Cross-Origin Resource Sharing (CORS) is a way for servers to share restricted resources, allowing them to be requested from a domain other than the one they are shared on. CORS uses HTTP headers.

In CORS, before sending the actual request to the server hosting the cross-origin resource, a “preflight” request is sent to check if the server allows such a request. The preflight request includes headers telling the server which HTTP method and headers the actual request implements and from which origin the request is coming.

We suggest adding our well-known domains amocrm.com and kommo.com to the whitelist of yours origins. It will let your widget access your API from the Kommo web application.

Note: Our old domain amocrm.com is still available for API requests.

Here is the example via PHP:

<?php
declare(strict_types=1);
namespace Security\Middleware;

use Illuminate\Support\Str;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CorsMiddleware implements MiddlewareInterface
{
    protected $origins = [
      'amocrm.com',
      'kommo.com',
    ];

    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $delegate
    ): ResponseInterface
    {
        $response = $delegate->handle($request);
        $origin = $request->getServerParams()['HTTP_ORIGIN'] ?? null;
        
        if ($origin && Str::endsWith($origin, $this->origins)) {
            $response = $response->withAddedHeader(
                'Access-Control-Allow-Origin',
                $origin
            )->withAddedHeader(
                'Access-Control-Allow-Credentials',
                'true'
            )->withAddedHeader(
                'Access-Control-Allow-Headers',
                'Content-Type, Accept, Authorization, Widget-Auth-Token'
            )->withAddedHeader(
                'Access-Control-Allow-Methods',
                'POST, GET, PATCH, DELETE, OPTION',
            );
        }        
        return $response;
    }
}