diff --git a/include/crow/middlewares/cors.h b/include/crow/middlewares/cors.h index 3f89c81e3..15e7d4213 100644 --- a/include/crow/middlewares/cors.h +++ b/include/crow/middlewares/cors.h @@ -1,4 +1,5 @@ #pragma once +#include "crow/common.h" #include "crow/http_request.h" #include "crow/http_response.h" #include "crow/routing.h" @@ -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; diff --git a/tests/unittest.cpp b/tests/unittest.cpp index d2ca615a4..594a33893 100644 --- a/tests/unittest.cpp +++ b/tests/unittest.cpp @@ -1960,6 +1960,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 "-"; @@ -1987,8 +1991,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");