FAQ - Help and questions

How do I configure CORS in axum, and why does the browser still block my request?

#axum#cors#tower-http#browserspublished 0 replies1 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Add tower-http CorsLayer with the allowed origin, methods and headers. The layer answers preflight OPTIONS requests itself. The browser, not the server, blocks a call from an origin that is not allowed: the server still answers, but without a matching Access-Control-Allow-Origin header.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot; tower-http 0.6.11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

CORS is a rule that browsers enforce for pages that call another origin. The server only sends headers that say what is allowed. With CorsLayer:

src/main.rsrust
use axum::{
    body::Body,
    http::{header, HeaderValue, Method, Request},
    routing::get,
    Router,
};
use tower::ServiceExt;
use tower_http::cors::CorsLayer;

async fn api() -> &'static str { "data" }

#[tokio::main]
async fn main() {
    let cors = CorsLayer::new()
        .allow_origin("https://app.example".parse::<HeaderValue>().unwrap())
        .allow_methods([Method::GET, Method::POST])
        .allow_headers([header::CONTENT_TYPE]);
    let app = Router::new().route("/api", get(api)).layer(cors);

    let preflight = Request::builder().method("OPTIONS").uri("/api")
        .header(header::ORIGIN, "https://app.example")
        .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
        .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "content-type")
        .body(Body::empty()).unwrap();
    let res = app.clone().oneshot(preflight).await.unwrap();
    println!("preflight -> {}", res.status());
    for (k, v) in res.headers() { println!("  {k}: {}", v.to_str().unwrap()); }

    for origin in ["https://app.example", "https://evil.example"] {
        let req = Request::get("/api").header(header::ORIGIN, origin).body(Body::empty()).unwrap();
        let res = app.clone().oneshot(req).await.unwrap();
        println!("GET from {origin} -> {} allow-origin={:?}", res.status(), res.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN));
    }
}
text
preflight -> 200 OK
  vary: origin, access-control-request-method, access-control-request-headers
  access-control-allow-methods: GET,POST
  access-control-allow-headers: content-type
  access-control-allow-origin: https://app.example
  allow: GET,HEAD
  content-length: 0
GET from https://app.example -> 200 OK allow-origin=Some("https://app.example")
GET from https://evil.example -> 200 OK allow-origin=Some("https://app.example")

Reading the output:

  • The preflight request (OPTIONS with Access-Control-Request-Method) was answered by the layer with status 200 and the allowed methods, headers and origin. The route itself has no OPTIONS handler.
  • A normal GET from the allowed origin got access-control-allow-origin: https://app.example.
  • A GET from https://evil.example also got status 200 and the body, with the allow-origin header still naming https://app.example. The server did not refuse it. The browser compares the header with the page's origin, sees they differ, and hides the response from the page's JavaScript.

So CORS does not protect the server from other callers (curl and other programs ignore it); it protects users' browsers.

Cargo.tomltoml
tower-http = { version = "0.6.11", features = ["cors"] }

Common mistakes#

  • Allowing every origin while also sending cookies. Name the exact origins you trust.
  • Forgetting a header the page sends (Authorization, Content-Type with JSON): list it in allow_headers, or the preflight fails.
  • Debugging CORS with curl. curl never applies the rule; read the browser console message and compare with the headers above.

Is CORS needed when the page and API share one origin?#

No. The rule applies only to calls to a different origin (scheme, host or port).

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet