DEV Community

Yaroslav Polyakov
Yaroslav Polyakov

Posted on • Edited on

apache2 allows CORS with credentials for any address

You cannot use '*' in Access-Control-Allow-Origin and use Access-Control-Allow-Credentials at same time. And this is actually makes sense, but during development this dirty hack is useful (for apache2):

SetEnvIf Origin "^http(s)?://.*$" REQUEST_ORIGIN=$0
Header always set Access-Control-Allow-Origin %{REQUEST_ORIGIN}e env=REQUEST_ORIGIN
Header always set Access-Control-Allow-Credentials true
Enter fullscreen mode Exit fullscreen mode

How it work in action (I'm using httpie instead of curl):

Example:

$ http -ph POST https://example.com/ Origin:https://google.com
HTTP/1.1 200 OK
Accept-Ranges: bytes
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://google.com
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 1039
Content-Type: text/html
Date: Thu, 12 Oct 2023 08:50:33 GMT
ETag: "9a1-6020521d58f80-gzip"
Keep-Alive: timeout=5, max=100
Last-Modified: Thu, 03 Aug 2023 13:55:26 GMT
Server: Apache/2.4.56 (Debian)
Strict-Transport-Security: max-age=31536000; includeSubDomains
Vary: Accept-Encoding
X-Content-Type-Options: nosniff
X-Frame-Options: disabled
Enter fullscreen mode Exit fullscreen mode

If you want it only for specific Origins:

    SetEnvIf Origin "^https?://(example.com|www.example.com)$" GOODORIGIN=$0
    Header set Access-Control-Allow-Origin %{GOODORIGIN}e env=GOODORIGIN
    Header set Access-Control-Allow-Credentials "true" env=GOODORIGIN
    Header merge Vary Origin
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs