18

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Bopsi
  • 2,090
  • 5
  • 36
  • 58

2 Answers2

12

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

Danny Sullivan
  • 3,626
  • 3
  • 30
  • 39
11

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.

estin
  • 3,051
  • 1
  • 24
  • 31
  • 3
    This is fine where I want to allow all. What if I want allow specifically 3 urls? say, abc.com, abc.uk, abc.org? – Bopsi Dec 16 '19 at 07:22
  • 2
    chain calls of `allowed_origin` on each allowed origin – estin Dec 16 '19 at 07:46
  • I get *error[E0599]: no function or associated item named `new` found for struct `Cors` in the current scope* – Evan Carroll Mar 08 '21 at 17:45
  • @EvanCarroll seems like actix-core was updated - use Cors::default() and checkout actual docs https://docs.rs/actix-cors/0.5.4/actix_cors/struct.Cors.html – estin Mar 09 '21 at 08:42
  • 3
    To do the same with the latest version (currently 0.5.4), use `Cors::permissive()` – tonayy Sep 30 '21 at 21:20