Skip to main content

Module cors

Module cors 

Source
Expand description

Cross-origin resource sharing (CORS)

Browsers only let a page read a cross-origin response when the server opts in. Cors implements that opt-in with the pitfalls handled:

  • the request’s Origin is checked against the allow list and echoed back (never “the first configured origin”), with Vary: Origin so caches do not serve one origin’s answer to another
  • credentials are never combined with a wildcard: with Cors::allow_any_origin the Access-Control-Allow-Credentials header is simply not sent, whatever else is configured
  • a preflight (OPTIONS with Origin and Access-Control-Request-Method) is answered by the middleware itself, even for paths without an OPTIONS route; preflights from unknown origins or for unlisted methods get 403
  • error responses carry the CORS headers too, so the browser shows the real status instead of an opaque network error
use std::time::Duration;
use ullun::cors::Cors;
use ullun::prelude::*;

App::new()
    .middleware(
        Cors::new()
            .allow_origin("https://app.example.com")
            .allow_credentials()
            .expose_headers(["x-request-id"])
            .max_age(Duration::from_secs(3600)),
    )
    .get("/", |_req: Request| async { Ok(Response::text("ok")) })
    .run("127.0.0.1:3000")
    .await
    .unwrap();

Structs§

Cors
CORS middleware, see the module documentation