CORS
note
This help topic is in development and will be updated in the future.
Ktor by default provides an interceptor for implementing proper support for Cross-Origin Resource Sharing (CORS).
tip
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
Basic
First of all, install the CORS feature into your application.
fun Application.main() {
...
install(CORS)
...
}
The default configuration to the CORS feature handles only GET
, POST
and HEAD
HTTP methods and the following headers:
HttpHeaders.Accept
HttpHeaders.AcceptLanguages
HttpHeaders.ContentLanguage
HttpHeaders.ContentType
Advanced
Here is an advanced example that demonstrates most of CORS-related API functions
fun Application.main() {
...
install(CORS)
{
method(HttpMethod.Options)
header(HttpHeaders.XForwardedProto)
anyHost()
host("my-host")
// host("my-host:80")
// host("my-host", subDomains = listOf("www"))
// host("my-host", schemes = listOf("http", "https"))
allowCredentials = true
allowNonSimpleContentTypes = true
maxAge = Duration.ofDays(1)
}
...
}
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()
: ExposesX-Http-Method-Override
header in the responseanyHost()
: Allows any host to access the resourceshost("hostname")
: Allows only the specified host to use CORS, it can have the port number, a list of subDomains or the supported schemes.allowCredentials
: IncludesAccess-Control-Allow-Credentials
header in the responseallowNonSimpleContentTypes
: IncluesContent-Type
request header to the white list for values other than simple content types.maxAge
: IncludesAccess-Control-Max-Age
header in the response with the given max age