Enable Cross-Origin Resource Sharing (CORS)

Ktor by default provides an interceptor for implementing proper support for Cross-Origin Resource Sharing (CORS).

Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries. If you serve public content, please consider using CORS to open it up for universal JavaScript / browser access.From enable-cors.org

This feature is defined in the class io.ktor.features.CORS and no additional artifacts are required.

Basic

First of all, install the CORS feature into your application.

  1. fun Application.main() {
  2. ...
  3. install(CORS)
  4. ...
  5. }

The default configuration to the CORS feature handles only GET, POST and HEAD HTTP methods and the following headers:

  1. HttpHeaders.Accept
  2. HttpHeaders.AcceptLanguages
  3. HttpHeaders.ContentLanguage
  4. HttpHeaders.ContentType

Advanced

Here is an advanced example that demonstrates most of CORS-related API functions

  1. fun Application.main() {
  2. ...
  3. install(CORS)
  4. {
  5. method(HttpMethod.Options)
  6. header(HttpHeaders.XForwardedProto)
  7. anyHost()
  8. host("my-host")
  9. // host("my-host:80")
  10. // host("my-host", subDomains = listOf("www"))
  11. // host("my-host", schemes = listOf("http", "https"))
  12. allowCredentials = true
  13. allowNonSimpleContentTypes = true
  14. maxAge = Duration.ofDays(1)
  15. }
  16. ...
  17. }

Configuration

  • method("HTTP_METHOD") : Includes this method to the white list of Http methods to use CORS.
  • header("header-name") : Includes this header to the white list of headers to use CORS.
  • exposeHeader("header-name") : Exposes this header in the response.
  • exposeXHttpMethodOverride() : Exposes X-Http-Method-Override header in the response
  • anyHost() : Allows any host to access the resources
  • host("hostname") : Allows only the specified host to use CORS, it can have the port number, a list of subDomains or the supported schemes.
  • allowCredentials : Includes Access-Control-Allow-Credentials header in the response
  • allowNonSimpleContentTypes: Inclues Content-Type request header to the white list for values other than simple content types.
  • maxAge: Includes Access-Control-Max-Age header in the response with the given max age