Skip to content

Commit

Permalink
Merge pull request #985 from softcom-su/origin-handling-fix
Browse files Browse the repository at this point in the history
Fixed handling of origin when allow_credentials enabled
  • Loading branch information
gittiver authored Feb 7, 2025
2 parents 3c82cda + 9d00070 commit 62d883b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
22 changes: 18 additions & 4 deletions include/crow/middlewares/cors.h
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#pragma once
#include "crow/common.h"
#include "crow/http_request.h"
#include "crow/http_response.h"
#include "crow/routing.h"
Expand Down Expand Up @@ -126,12 +127,25 @@ namespace crow
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
bool origin_set = false;

if (req.method != HTTPMethod::Options)
{
if (allow_credentials_)
{
set_header_no_override("Access-Control-Allow-Credentials", "true", res);
if (origin_ == "*")
{
set_header_no_override("Access-Control-Allow-Origin", req.get_header_value("Origin"), res);
origin_set = true;
}
}
}

if( !origin_set){
set_header_no_override("Access-Control-Allow-Origin", origin_, res);
}
}

bool ignore_ = false;
Expand Down
12 changes: 11 additions & 1 deletion tests/unittest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1997,6 +1997,10 @@ TEST_CASE("middleware_cors")
return "-";
});

CROW_ROUTE(app, "/auth-origin").methods(crow::HTTPMethod::Post)([&](const request&) {
return "-";
});

CROW_ROUTE(app, "/expose")
([&](const request&) {
return "-";
Expand Down Expand Up @@ -2024,8 +2028,14 @@ TEST_CASE("middleware_cors")
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");
"GET /auth-origin\r\nOrigin: test-client\r\n\r\n");
CHECK(resp.find("Access-Control-Allow-Origin: test-client") != std::string::npos);
CHECK(resp.find("Access-Control-Allow-Credentials: true") != std::string::npos);

resp = HttpClient::request(LOCALHOST_ADDRESS, port,
"OPTIONS /auth-origin / HTTP/1.1 \r\n\r\n");
CHECK(resp.find("Access-Control-Allow-Origin: *") != std::string::npos);
CHECK(resp.find("Access-Control-Allow-Credentials: true") == std::string::npos);

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

0 comments on commit 62d883b

Please sign in to comment.