From 132b1375104366d3364a5679ce190a6be663eff0 Mon Sep 17 00:00:00 2001 From: bugdea1er Date: Tue, 7 Jan 2025 14:44:56 +0300 Subject: [PATCH] Add an option to expose headers for CORS --- include/crow/middlewares/cors.h | 18 ++++++++++++++++++ tests/unittest.cpp | 12 +++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/include/crow/middlewares/cors.h b/include/crow/middlewares/cors.h index fd5ab072c..ed8ae6782 100644 --- a/include/crow/middlewares/cors.h +++ b/include/crow/middlewares/cors.h @@ -51,6 +51,22 @@ namespace crow return *this; } + /// Set Access-Control-Expose-Headers. Default is none + CORSRules& expose(const std::string& header) + { + add_list_item(exposed_headers_, header); + return *this; + } + + /// Set Access-Control-Expose-Headers. Default is none + template + CORSRules& expose(const std::string& header, Headers... header_list) + { + add_list_item(exposed_headers_, header); + expose(header_list...); + return *this; + } + /// Set Access-Control-Max-Age. Default is none CORSRules& max_age(int max_age) { @@ -108,6 +124,7 @@ namespace crow 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); } @@ -117,6 +134,7 @@ namespace crow std::string origin_ = "*"; std::string methods_ = "*"; std::string headers_ = "*"; + std::string exposed_headers_; std::string max_age_; bool allow_credentials_ = false; diff --git a/tests/unittest.cpp b/tests/unittest.cpp index af0adedc4..2d3945dd2 100644 --- a/tests/unittest.cpp +++ b/tests/unittest.cpp @@ -1930,7 +1930,6 @@ TEST_CASE("middleware_cookieparser_format") TEST_CASE("middleware_cors") { - App app; auto& cors = app.get_middleware(); @@ -1938,6 +1937,8 @@ TEST_CASE("middleware_cors") cors .prefix("/origin") .origin("test.test") + .prefix("/expose") + .expose("exposed-header") .prefix("/nocors") .ignore(); // clang-format on @@ -1952,6 +1953,11 @@ TEST_CASE("middleware_cors") return "-"; }); + CROW_ROUTE(app, "/expose") + ([&](const request&) { + return "-"; + }); + CROW_ROUTE(app, "/nocors/path") ([&](const request&) { return "-"; @@ -1973,6 +1979,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 /expose\r\n\r\n"); + CHECK(resp.find("Access-Control-Expose-Headers: exposed-header") != std::string::npos); + resp = HttpClient::request(LOCALHOST_ADDRESS, port, "GET /nocors/path\r\n\r\n");