Skip to content

Commit

Permalink
Merge pull request #979 from bugdea1er/cors-origin
Browse files Browse the repository at this point in the history
Credential is not supported if Allowed Origin is '*'
  • Loading branch information
gittiver authored Jan 9, 2025
2 parents 77eda0d + 2b80670 commit c27c5ce
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
11 changes: 8 additions & 3 deletions include/crow/middlewares/cors.h
Original file line number Diff line number Diff line change
Expand Up @@ -118,15 +118,20 @@ namespace crow
}

/// Set response headers
void apply(crow::response& res)
void apply(const request& req, response& res)
{
if (ignore_) return;
set_header_no_override("Access-Control-Allow-Origin", origin_, res);

set_header_no_override("Access-Control-Allow-Methods", methods_, res);
set_header_no_override("Access-Control-Allow-Headers", headers_, res);
set_header_no_override("Access-Control-Expose-Headers", exposed_headers_, res);
set_header_no_override("Access-Control-Max-Age", max_age_, res);
if (allow_credentials_) set_header_no_override("Access-Control-Allow-Credentials", "true", res);

if (allow_credentials_ && origin_ == "*")
set_header_no_override("Access-Control-Allow-Origin", req.get_header_value("Origin"), res);
else
set_header_no_override("Access-Control-Allow-Origin", origin_, res);
}

bool ignore_ = false;
Expand Down Expand Up @@ -158,7 +163,7 @@ namespace crow
void after_handle(crow::request& req, crow::response& res, context& /*ctx*/)
{
auto& rule = find_rule(req.url);
rule.apply(res);
rule.apply(req, res);
}

/// Handle CORS on a specific prefix path
Expand Down
11 changes: 11 additions & 0 deletions tests/unittest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1937,6 +1937,8 @@ TEST_CASE("middleware_cors")
cors
.prefix("/origin")
.origin("test.test")
.prefix("/auth-origin")
.allow_credentials()
.prefix("/expose")
.expose("exposed-header")
.prefix("/nocors")
Expand All @@ -1953,6 +1955,11 @@ TEST_CASE("middleware_cors")
return "-";
});

CROW_ROUTE(app, "/auth-origin")
([&](const request&) {
return "-";
});

CROW_ROUTE(app, "/expose")
([&](const request&) {
return "-";
Expand All @@ -1979,6 +1986,10 @@ TEST_CASE("middleware_cors")
"GET /origin\r\n\r\n");
CHECK(resp.find("Access-Control-Allow-Origin: test.test") != std::string::npos);

resp = HttpClient::request(LOCALHOST_ADDRESS, port,
"GET /auth-origin\r\nOrigin: test-client\r\n\r\n");
CHECK(resp.find("Access-Control-Allow-Origin: test-client") != std::string::npos);

resp = HttpClient::request(LOCALHOST_ADDRESS, port,
"GET /expose\r\n\r\n");
CHECK(resp.find("Access-Control-Expose-Headers: exposed-header") != std::string::npos);
Expand Down

0 comments on commit c27c5ce

Please sign in to comment.