CORS
suggest changeCross-Origin Resource Sharing (CORS) is a browser mechanism that lets a server say which other web origins may read its responses. An origin is the triple scheme + host + port: https://app.example.com and https://api.example.com are different origins, and so are http://localhost:3000 and http://localhost:8080.
By default browsers enforce the same-origin policy: JavaScript on https://app.example.com can send a fetch to https://api.example.com, but it cannot read the response unless the API answers with the right Access-Control-* headers. CORS is how a Kotlin backend opts in.
Key facts to keep in mind:
- CORS is enforced only by browsers.
curl, Ktor Client, OkHttp or another server ignore it completely. It is not an authentication or authorization mechanism. - The server decides, the browser enforces. A missing header does not stop the request from reaching your server; it stops the page from reading the answer.
- CORS errors show up in the browser console, not in your server logs, so you debug them by inspecting response headers.
The HTTP middleware article shows a short install(CORS) example; this article explains what the plugin actually does and how to configure it correctly.
Simple requests vs. preflight requests
A request is simple when all of these are true:
- the method is
GET,HEADorPOST - it only sets "safelisted" headers such as
Accept,Accept-Language,Content-LanguageandContent-Type Content-Type, if present, isapplication/x-www-form-urlencoded,multipart/form-dataortext/plain
For a simple request the browser sends it directly with an Origin header and checks the response:
GET /api/items HTTP/1.1
Origin: https://app.example.com
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com
Vary: Origin
Anything else - PUT, DELETE, PATCH, Content-Type: application/json, an Authorization header, custom headers like X-Request-Id - triggers a preflight: an OPTIONS request that asks for permission before the real request is sent.
OPTIONS /api/items/42 HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type, authorization
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 3600
Vary: Origin
Only if the preflight succeeds does the browser send the actual PUT, which must again carry Access-Control-Allow-Origin.
The headers
| Header | Direction | Meaning |
|---|---|---|
Origin |
request | Origin of the page making the request |
Access-Control-Request-Method |
preflight request | Method the real request will use |
Access-Control-Request-Headers |
preflight request | Non-safelisted headers the real request will send |
Access-Control-Allow-Origin |
response | The allowed origin, or * |
Access-Control-Allow-Methods |
preflight response | Allowed methods |
Access-Control-Allow-Headers |
preflight response | Allowed request headers |
Access-Control-Allow-Credentials |
response | true if cookies / auth may be included |
Access-Control-Expose-Headers |
response | Response headers JavaScript may read beyond the safelisted ones |
Access-Control-Max-Age |
preflight response | Seconds the browser may cache the preflight result |
Vary: Origin |
response | Tells caches the response depends on Origin |
Access-Control-Allow-Origin holds exactly one origin or *. To allow several origins the server must compare the incoming Origin against an allow-list and echo back the matching one, together with Vary: Origin.
Credentials
Cookies and HTTP authentication are sent cross-origin only if the client opts in (fetch(url, { credentials: "include" })) and the server responds with Access-Control-Allow-Credentials: true. In that case the browser forbids wildcards: Access-Control-Allow-Origin, Access-Control-Allow-Headers and Access-Control-Allow-Methods must not be *. You must echo the concrete origin.
Note that cookies also need SameSite=None; Secure to be sent on cross-site requests; CORS alone is not enough.
Ktor: the CORS plugin
Add the dependency (Ktor 3.x):
dependencies {
val ktorVersion = "3.6.0"
implementation("io.ktor:ktor-server-core:$ktorVersion")
implementation("io.ktor:ktor-server-netty:$ktorVersion")
implementation("io.ktor:ktor-server-cors:$ktorVersion")
testImplementation("io.ktor:ktor-server-test-host:$ktorVersion")
testImplementation(kotlin("test"))
}
A production-style configuration:
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.module() {
install(CORS) {
// Origins: host without scheme; schemes and subdomains are separate
allowHost("app.example.com", schemes = listOf("https"))
allowHost("example.com", schemes = listOf("https"), subDomains = listOf("admin"))
allowHost("localhost:3000") // dev frontend; schemes default to listOf("http")
// GET, POST and HEAD are allowed by default
allowMethod(HttpMethod.Put)
allowMethod(HttpMethod.Patch)
allowMethod(HttpMethod.Delete)
// Allows Content-Type: application/json (non-simple content types)
allowHeader(HttpHeaders.ContentType)
allowHeader(HttpHeaders.Authorization)
allowHeader("X-Request-Id")
// Let JavaScript read these response headers
exposeHeader(HttpHeaders.ETag)
exposeHeader("X-Total-Count")
allowCredentials = true
maxAgeInSeconds = 3600
}
routing {
get("/api/items") {
call.response.header("X-Total-Count", "2")
call.respondText("""[{"id":1},{"id":2}]""", ContentType.Application.Json)
}
put("/api/items/{id}") {
call.respond(HttpStatusCode.NoContent)
}
}
}
fun main() {
embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}
Notes on the Ktor plugin:
- The import is
io.ktor.server.plugins.cors.routing.*. The olderio.ktor.server.plugins.cors.*package is deprecated. - The plugin answers preflight
OPTIONSrequests itself; you do not needoptions { }routes. - Requests whose origin is not allowed get
403 Forbidden. anyHost()allows every origin. Use it only for truly public, credential-less APIs.- For dynamic rules use predicates:
allowOrigins { origin -> origin.endsWith(".preview.example.com") }andallowHeaders { name -> name.startsWith("X-") }. - Install CORS before other plugins that may reject a request (for example authentication), so that error responses still carry the CORS headers and the browser shows the real status instead of a generic CORS error.
Reading allowed origins from configuration keeps environments separate:
fun Application.configureCors() {
val origins = environment.config.propertyOrNull("cors.origins")?.getList().orEmpty()
install(CORS) {
origins.forEach { origin ->
val url = Url(origin) // e.g. "https://app.example.com"
val host = if (url.specifiedPort == 0) url.host else "${url.host}:${url.port}"
allowHost(host, schemes = listOf(url.protocol.name))
}
allowHeader(HttpHeaders.ContentType)
allowCredentials = true
}
}
Spring Boot
Spring Boot 3 (Spring Framework 6) offers three levels of configuration.
Per controller or method with @CrossOrigin:
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/api/items")
@CrossOrigin(origins = ["https://app.example.com"], maxAge = 3600)
class ItemController {
@GetMapping
fun list() = listOf(mapOf("id" to 1))
@CrossOrigin(origins = ["https://admin.example.com"], allowCredentials = "true")
@DeleteMapping("/{id}")
fun delete(@PathVariable id: Long) { /* ... */ }
}
Globally for Spring MVC with WebMvcConfigurer:
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
@Configuration
class WebConfig : WebMvcConfigurer {
override fun addCorsMappings(registry: CorsRegistry) {
registry.addMapping("/api/**")
.allowedOrigins("https://app.example.com")
.allowedOriginPatterns("https://*.preview.example.com")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE")
.allowedHeaders("Content-Type", "Authorization")
.exposedHeaders("X-Total-Count")
.allowCredentials(true)
.maxAge(3600)
}
}
Use allowedOriginPatterns (not allowedOrigins("*")) when you need wildcards together with credentials; Spring then echoes the matching origin.
With Spring Security CORS must be handled by the security filter chain, otherwise preflight requests are rejected as unauthenticated before MVC sees them. Expose a CorsConfigurationSource bean and enable cors:
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.Customizer
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.web.SecurityFilterChain
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.CorsConfigurationSource
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
@Configuration
class SecurityConfig {
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val config = CorsConfiguration().apply {
allowedOrigins = listOf("https://app.example.com")
allowedMethods = listOf("GET", "POST", "PUT", "DELETE")
allowedHeaders = listOf("Content-Type", "Authorization")
exposedHeaders = listOf("X-Total-Count")
allowCredentials = true
maxAge = 3600L
}
return UrlBasedCorsConfigurationSource().apply {
registerCorsConfiguration("/api/**", config)
}
}
@Bean
fun filterChain(http: HttpSecurity): SecurityFilterChain {
http
.cors(Customizer.withDefaults()) // picks up the corsConfigurationSource bean
.authorizeHttpRequests { it.anyRequest().authenticated() }
return http.build()
}
}
A hand-written implementation
Writing CORS yourself is rarely necessary, but it shows exactly what the plugins do. This Ktor application plugin handles an origin allow-list, preflights and credentials:
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
class SimpleCorsConfig {
var allowedOrigins: Set<String> = emptySet() // full origins: "https://app.example.com"
var allowedMethods: Set<String> = setOf("GET", "POST", "PUT", "DELETE")
var allowedHeaders: Set<String> = setOf("content-type", "authorization")
var allowCredentials: Boolean = false
var maxAgeSeconds: Long = 600
}
val SimpleCors = createApplicationPlugin("SimpleCors", ::SimpleCorsConfig) {
val origins = pluginConfig.allowedOrigins
val methods = pluginConfig.allowedMethods
val headers = pluginConfig.allowedHeaders.map { it.lowercase() }.toSet()
val credentials = pluginConfig.allowCredentials
val maxAge = pluginConfig.maxAgeSeconds
onCall { call ->
val origin = call.request.header(HttpHeaders.Origin) ?: return@onCall // not a CORS request
call.response.headers.append(HttpHeaders.Vary, HttpHeaders.Origin)
if (origin !in origins) return@onCall // no CORS headers: browser blocks the read
call.response.headers.append(HttpHeaders.AccessControlAllowOrigin, origin)
if (credentials) {
call.response.headers.append(HttpHeaders.AccessControlAllowCredentials, "true")
}
if (call.request.httpMethod != HttpMethod.Options) return@onCall
val requestedMethod = call.request.header(HttpHeaders.AccessControlRequestMethod)
?: return@onCall // plain OPTIONS request, not a preflight
val requestedHeaders = call.request.header(HttpHeaders.AccessControlRequestHeaders)
?.split(",")?.map { it.trim().lowercase() }?.filter { it.isNotEmpty() }.orEmpty()
if (requestedMethod !in methods || !headers.containsAll(requestedHeaders)) {
call.respond(HttpStatusCode.Forbidden)
return@onCall
}
call.response.headers.append(HttpHeaders.AccessControlAllowMethods, methods.joinToString(", "))
call.response.headers.append(HttpHeaders.AccessControlAllowHeaders, headers.joinToString(", "))
call.response.headers.append(HttpHeaders.AccessControlMaxAge, maxAge.toString())
call.respond(HttpStatusCode.NoContent) // answer the preflight; routing never runs
}
}
// install(SimpleCors) { allowedOrigins = setOf("https://app.example.com"); allowCredentials = true }
The origin comparison is an exact string match against full origins, which avoids the classic bug of prefix or substring matching (https://app.example.com.evil.net must not match).
Common mistakes
*with credentials.Access-Control-Allow-Origin: *plusAccess-Control-Allow-Credentials: trueis rejected by browsers. Echo a specific origin.- Reflecting any
Originblindly. Echoing whatever origin arrives, with credentials enabled, lets any website make authenticated requests as your users. Always check an allow-list. - Sloppy matching.
origin.contains("example.com")orstartsWith("https://example.com")match attacker-controlled domains. Parse the URL and compare host exactly or by proper suffix (.example.com). - Forgetting
Vary: Origin. When the response depends onOrigin, a CDN or proxy may otherwise serve one origin's headers to another. - Auth runs before CORS. A preflight carries no credentials. If authentication rejects
OPTIONSwith 401, the browser reports a CORS error. - Missing
Content-Typein allowed headers.fetchwith a JSON body sendsContent-Type: application/json, which needsallowHeader(HttpHeaders.ContentType)in Ktor. - Expecting to read custom response headers. JavaScript sees only safelisted response headers unless you list others in
Access-Control-Expose-Headers. - Trailing slash or wrong port in the origin.
https://app.example.com/is not an origin;http://localhost:3000andhttp://localhost:5173are different origins. - Using CORS as security. Non-browser clients ignore it. Protect endpoints with real authentication and CSRF defenses.
Testing with curl
Simulate a simple request by adding an Origin header:
curl -i -H "Origin: https://app.example.com" http://localhost:8080/api/items
Simulate a preflight:
curl -i -X OPTIONS http://localhost:8080/api/items/42 \
-H "Origin: https://app.example.com" \
-H "Access-Control-Request-Method: PUT" \
-H "Access-Control-Request-Headers: content-type, authorization"
Check a disallowed origin (Ktor responds with 403 and no Access-Control-Allow-Origin):
curl -i -H "Origin: https://evil.example.net" http://localhost:8080/api/items
Testing with testApplication
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.*
class CorsTest {
@Test
fun `preflight from allowed origin succeeds`() = testApplication {
application { module() }
val resp = client.options("/api/items/42") {
header(HttpHeaders.Origin, "https://app.example.com")
header(HttpHeaders.AccessControlRequestMethod, "PUT")
header(HttpHeaders.AccessControlRequestHeaders, "content-type")
}
assertEquals(HttpStatusCode.OK, resp.status)
assertEquals("https://app.example.com", resp.headers[HttpHeaders.AccessControlAllowOrigin])
assertEquals("true", resp.headers[HttpHeaders.AccessControlAllowCredentials])
}
@Test
fun `unknown origin is rejected`() = testApplication {
application { module() }
val resp = client.get("/api/items") {
header(HttpHeaders.Origin, "https://evil.example.net")
}
assertEquals(HttpStatusCode.Forbidden, resp.status)
assertNull(resp.headers[HttpHeaders.AccessControlAllowOrigin])
}
}
Ktor's built-in plugin answers a successful preflight with 200 OK; the hand-written version above uses 204 No Content. Browsers accept any 2xx status.