==== CorsHandler

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS[Cross-Origin Resource Sharing (CORS)] is a mechanism that uses HTTP headers to grant a web application running at one origin permission to access resources from a server at a different origin.

By default, **Jooby rejects all cross-origin requests**. To enable them, you must install the javadoc:handler.CorsHandler[].

.CORS Usage
[source, java, role = "primary"]
----
import io.jooby.handler.CorsHandler;

{
  use(new CorsHandler()); // <1>
  
  path("/api", () -> {
    // API methods
  });
}
----

.Kotlin
[source, kotlin, role = "secondary"]
----
import io.jooby.handler.CorsHandler

{
  use(CorsHandler())      // <1>
  
  path("/api") {
    // API methods
  }
}
----

<1> Install the `CorsHandler` with default options.

The default configuration is:

* **Origin:** `*` (All origins)
* **Credentials:** `true`
* **Methods:** `GET`, `POST`
* **Headers:** `X-Requested-With`, `Content-Type`, `Accept`, and `Origin`
* **Max Age:** `30m`

===== Customizing CORS Options

To customize these settings, use the javadoc:handler.Cors[] class:

.CORS Options
[source, java, role = "primary"]
----
import io.jooby.handler.Cors;
import io.jooby.handler.CorsHandler;

{
  Cors cors = new Cors()
     .setMethods("GET", "POST", "PUT", "DELETE"); // <1>

  use(new CorsHandler(cors));                     // <2>
}
----

.Kotlin
[source, kotlin, role = "secondary"]
----
import io.jooby.handler.CorsHandler
import io.jooby.cors

{
  val cors = cors {
    methods = listOf("GET", "POST", "PUT", "DELETE") // <1>
  }
  use(CorsHandler(cors))                             // <2>
}
----

<1> Specify the allowed HTTP methods.
<2> Pass the custom configuration to the `CorsHandler`.

===== Configuration-based CORS

You can also define your CORS settings directly in your `application.conf` file:

.application.conf
[source, properties]
----
cors {
  origin: "https://example.com"
  credentials: true
  methods: [GET, POST, PUT]
  headers: [Content-Type, X-App-Version]
  maxAge: 30m
  exposedHeaders: [X-Custom-Header]
}
----

Then, load the configuration into the handler:

.Loading from Config
[source, java, role = "primary"]
----
import io.jooby.handler.Cors;
import io.jooby.handler.CorsHandler;

{
  Cors cors = Cors.from(getConfig()); // <1>
  use(new CorsHandler(cors));
}
----

.Kotlin
[source, kotlin, role = "secondary"]
----
import io.jooby.handler.Cors
import io.jooby.handler.CorsHandler

{
  val cors = Cors.from(config)        // <1>
  use(CorsHandler(cors))
}
----

<1> Loads the CORS options defined in the `cors` namespace of your configuration file.
