jvdwrf / axum-tonic

35 stars 9 forks source link

How to have permissive CORS? #3

Closed Swoorup closed 1 year ago

Swoorup commented 1 year ago

I tried running a simple Echo example from the tonic sources using this axum. It seems I am unable to get the CORS policy working any ideas?

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8080/grpc.Echo/UnaryEcho. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8080/grpc.Echo/UnaryEcho. (Reason: CORS request did not succeed). Status code: (null).
async fn main() -> Result<(), Box<dyn std::error::Error>> {
  let echo_service = tonic_web::config()
    .allow_all_origins()
    .expose_headers([ACCESS_CONTROL_ALLOW_ORIGIN])
    .enable(EchoServer::new(Echo::default()));

  let cors = CorsLayer::new()
    .allow_methods(Any)
    .allow_headers(Any)
    .expose_headers(Any)
    .allow_origin(Any);

  let grpc_router = Router::new()
    .nest_tonic(echo_service)
    .layer(cors.clone());

  let rest_router = Router::new()
    .route("/users", post(user_service::create_user))
    .layer(cors.clone())
    .merge(SwaggerUi::new("/swagger-ui/*tail").url("/api-doc/openapi.json", ApiDoc::openapi()));

  let service = RestGrpcService::new(rest_router, grpc_router).into_make_service();

  axum::Server::bind(&"127.0.0.1:8080".parse().unwrap()).serve(service).await.unwrap();

  Ok(())
Swoorup commented 1 year ago

I can get it working without axum-tonic using tonic-web. But....

  let addr = "127.0.0.1:8080".parse().unwrap();

  let echo_service = tonic_web::config()
    .allow_all_origins()
    .allow_credentials(true)
    .expose_headers([ACCESS_CONTROL_ALLOW_ORIGIN])
    .enable(EchoServer::new(Echo::default()));

  Server::builder().accept_http1(true).add_service(echo_service).serve(addr).await;
Swoorup commented 1 year ago

Solved without using axum-tonic: https://github.com/hyperium/tonic/discussions/1111#discussioncomment-4069201