Hi, can you help a poor CORS soul out? ktor 1.6.8 ...
# ktor
h
Hi, can you help a poor CORS soul out? ktor 1.6.8 The request (external) adds
Access-Control-Request-Headers:x-api-key
to the
OPTIONS
preflight request. But my server always rejects it with 403 Forbidden. When I mimic the request and remove that header it returns 200 OK and everything works. I cannot figure out how to allow that header (and value). Things I tried:
Copy code
install(CORS)
    {
        method(HttpMethod.Options)
        method(HttpMethod.Put)
        method(HttpMethod.Delete)
        method(HttpMethod.Get)
        method(HttpMethod.Head)
        header(HttpHeaders.Authorization)
        header(HttpHeaders.AccessControlRequestHeaders)
        header(HttpHeaders.ContentType)
        exposeHeader("x-api-key")
    }
Application.conf
Copy code
cors {
      allowed-request-headers: "Access-Control-Request-Headers"
    }
I tried debugging, but no stop marks trigger, and I can't find an online source describing this problem.
a
You can call the
allowHeaders
method to allow headers by the given predicate, but I am unsure if this method exists in Ktor 1.*:
Copy code
install(CORS) {
    // ...
    allowHeaders {
        it == "x-api-key"
    }
}
h
Thank you for the reply. I notice that
Origin
also plays a role if the preflight is rejected or not. I thought that
anyHost()
would allow for all origins.
Now the exact same request from postman works on localhost, but not from DEV deplyoment. Weird.
Okay, I don't know what exactly caused it to work. But it does now.
Copy code
install(CORS) {
    method(HttpMethod.Options)
    method(HttpMethod.Put)
    method(HttpMethod.Delete)
    method(HttpMethod.Get)
    method(HttpMethod.Head)
    header(HttpHeaders.Authorization)
    header(HttpHeaders.AccessControlRequestHeaders)
    header(HttpHeaders.AccessControlAllowHeaders)
    header(HttpHeaders.ContentType)
    header(HttpHeaders.AccessControlAllowOrigin)
    header(HttpHeaders.AccessControlAllowMethods)
    header(HttpHeaders.Origin)
    header(HttpHeaders.Referrer)
    header("x-api-key")
    exposeHeader("x-api-key")
}
Thanks 😄