tower-rs / tower-http

HTTP specific Tower utilities.
702 stars 165 forks source link

AllowOrigin::list() does not work as expected. #392

Closed zishon closed 1 year ago

zishon commented 1 year ago

Bug Report

Version

tower-http: 0.4.3

Platform

win10-64bit pro

Crates

axum 0.6.19 http 0.2.9

Description

AllowOrigin::list does not function as expected

I tried this code:

use axum::{Extension, Router};
use axum::routing::{get, post};
use http::HeaderValue;
use tower_http::cors::{AllowHeaders, AllowMethods, AllowOrigin, Any, CorsLayer};

async fn aaa() {
}

#[tokio::main]
async fn main() {
    //it does not work.
    //let cors = CorsLayer::new().allow_methods(Any).allow_origin(AllowOrigin::list([
    //    "http://127.0.0.1:3000".parse::<HeaderValue>().unwrap(),
    //    "http://api.example.com:3000".parse::<HeaderValue>().unwrap(),
    //]));

    //it works.
    let cors = CorsLayer::new().allow_methods(Any).allow_origin(
        "http://127.0.0.1:3000".parse::<HeaderValue>().unwrap(),
    );

    let app = Router::new()
        .route("/aaa", get(aaa).layer(cors));

    // run it with hyper on localhost:3000
    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

I expected to see this happen: when I curl as :curl -X OPTIONS http://127.0.0.1:3000/aaa -vvv, expected there is an response header: access-control-allow-origin: http://127.0.0.1:3000

Instead, this happened: but if I use AllowOrigin::list(),then I see no access-control-allow-origin response header.

jplatte commented 1 year ago

This is working as expected, since curl does not send an origin header in the request by default no access-control-allow-origin is sent back. From MDN:

Only a single origin can be specified. If the server supports clients from multiple origins, it must return the origin for the specific client making the request.

If you use curl -i -X OPTIONS -H "origin: http://api.example.com:3000" http://127.0.0.1:3000/aaa you should see the CORS header being returned.