Boost C++ Libraries

PrevUpHomeNext

Struct cors

boost::taar::cors — Cross-Origin Resource Sharing policy.

Synopsis

// In header: <boost/taar/core/cors.hpp>


struct cors {

  // public member functions
  bool origin_allowed(std::string_view) const;
  template<typename Request, typename Response> 
    void apply(Request const &, Response &) const;
  auto preflight_handler() const;
  std::function< void(boost::beast::http::request_header<> const &, boost::beast::http::response_header<> &)> 
  response_filter() const;

  // public data members
  std::vector< std::string > allowed_origins;  // Origins that may call. 
  std::vector< std::string > allowed_methods;
  std::vector< std::string > allowed_headers;
  std::vector< std::string > exposed_headers;
  bool allow_credentials;
  std::chrono::seconds max_age;
};

Description

Two pieces plug into a session: preflight_handler answers OPTIONS requests, and response_filter stamps the CORS headers on every other response (install it with basic_http::set_response_filter). Defaults allow any origin without credentials and the headers the MCP transport needs.

taar::cors cors;
cors.allowed_origins = {"http://localhost:3000"};
cors.allow_credentials = true;

session.register_request_handler(method == http::verb::options, cors.preflight_handler());
session.set_response_filter(cors.response_filter());

cors public member functions

  1. bool origin_allowed(std::string_view origin) const;
    True if origin may call.

    The wildcard does not count when credentials are allowed: a credentialed response must name the origin.

  2. template<typename Request, typename Response> 
      void apply(Request const & request, Response & response) const;
    Add the CORS response headers for request to response, if its Origin is allowed.
  3. auto preflight_handler() const;
    A handler for OPTIONS preflight requests: 204 with the allow headers, or 403.
  4. std::function< void(boost::beast::http::request_header<> const &, boost::beast::http::response_header<> &)> 
    response_filter() const;
    A response filter for basic_http::set_response_filter applying apply to every response.

cors public public data members

  1. std::vector< std::string > allowed_origins;

    "*" allows any origin without credentials; with allow_credentials the wildcard is ignored and origins must be listed explicitly (the matching one is echoed with Vary: Origin).


PrevUpHomeNext