Bopsi
Bopsi

Reputation: 2446

How do I configure actix-web to accept CORS requests from any origin?

I am building a REST API with actix-web. How do I configure CORS to accept requests from any origin?

Cors::new() // <- Construct CORS middleware builder
    .allowed_origin("localhost:8081")
    .allowed_methods(vec!["GET", "POST"])
    .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
    .allowed_header(http::header::CONTENT_TYPE)
    .max_age(3600)

The above code works from the web at localhost:8081, but not from 0.0.0.0:8081 or 127.0.0.1:8081. I tried "*" to allow all, but it's not working. How do I allow all, or at least allow a specific origin and then pass multiple URLs?

Upvotes: 19

Views: 17209

Answers (3)

javad bat
javad bat

Reputation: 5236

you can add origins multiple times:

let cors = Cors::default()
            .allowed_origin("http://localhost:3000")
            .allowed_origin("http://localhost:3200")
            .allowed_origin("https://your-origin.com")
            .allowed_origin("https://your-origin2.com")
            .allowed_methods(vec!["GET", "POST", "DELETE", "PUT"])
            .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT,http::header::CONTENT_TYPE])
            .max_age(3600);

Upvotes: 1

Danny Sullivan
Danny Sullivan

Reputation: 3844

Starting from actix-cors = "0.5.0", you can use:

Cors::permissive()

However, they recommend against using it in production: https://docs.rs/actix-cors/latest/actix_cors/struct.Cors.html#method.permissive

Upvotes: 15

estin
estin

Reputation: 3121

By default All origins is allowed

This is my simple CORS setup (allow all origins and methods + allow send credentials)

Cors::new().supports_credentials() 

You can start with it, and disallow methods, origins and headers step-by-step.

Upvotes: 12

Related Questions