Skip to content

Commit aa79927

Browse files
TiARETiKDmitriy Zaytsev
authored andcommitted
"Allow-Origin" behavior in OPTIONS requests fixed
1 parent 08f2b36 commit aa79927

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

include/crow/middlewares/cors.h

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#pragma once
2+
#include "crow/common.h"
23
#include "crow/http_request.h"
34
#include "crow/http_response.h"
45
#include "crow/routing.h"
@@ -126,10 +127,14 @@ namespace crow
126127
set_header_no_override("Access-Control-Allow-Headers", headers_, res);
127128
set_header_no_override("Access-Control-Expose-Headers", exposed_headers_, res);
128129
set_header_no_override("Access-Control-Max-Age", max_age_, res);
129-
if (allow_credentials_) set_header_no_override("Access-Control-Allow-Credentials", "true", res);
130-
131-
if (allow_credentials_ && origin_ == "*")
132-
set_header_no_override("Access-Control-Allow-Origin", req.get_header_value("Origin"), res);
130+
if (req.method != HTTPMethod::OPTIONS)
131+
{
132+
if (allow_credentials_) set_header_no_override("Access-Control-Allow-Credentials", "true", res);
133+
if (allow_credentials_ && origin_ == "*")
134+
set_header_no_override("Access-Control-Allow-Origin", req.get_header_value("Origin"), res);
135+
else
136+
set_header_no_override("Access-Control-Allow-Origin", origin_, res);
137+
}
133138
else
134139
set_header_no_override("Access-Control-Allow-Origin", origin_, res);
135140
}

tests/unittest.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1960,6 +1960,10 @@ TEST_CASE("middleware_cors")
19601960
return "-";
19611961
});
19621962

1963+
CROW_ROUTE(app, "/auth-origin").methods(crow::HTTPMethod::Post)([&](const request&) {
1964+
return "-";
1965+
});
1966+
19631967
CROW_ROUTE(app, "/expose")
19641968
([&](const request&) {
19651969
return "-";
@@ -1987,8 +1991,14 @@ TEST_CASE("middleware_cors")
19871991
CHECK(resp.find("Access-Control-Allow-Origin: test.test") != std::string::npos);
19881992

19891993
resp = HttpClient::request(LOCALHOST_ADDRESS, port,
1990-
"GET /auth-origin\r\nOrigin: test-client\r\n\r\n");
1994+
"GET /auth-origin\r\nOrigin: test-client\r\n\r\n");
19911995
CHECK(resp.find("Access-Control-Allow-Origin: test-client") != std::string::npos);
1996+
CHECK(resp.find("Access-Control-Allow-Credentials: true") != std::string::npos);
1997+
1998+
resp = HttpClient::request(LOCALHOST_ADDRESS, port,
1999+
"OPTIONS /auth-origin / HTTP/1.1 \r\n\r\n");
2000+
CHECK(resp.find("Access-Control-Allow-Origin: *") != std::string::npos);
2001+
CHECK(resp.find("Access-Control-Allow-Credentials: true") == std::string::npos);
19922002

19932003
resp = HttpClient::request(LOCALHOST_ADDRESS, port,
19942004
"GET /expose\r\n\r\n");

0 commit comments

Comments
 (0)