Hi! Is it possible to add path based authorisation...
# ktor
t
Hi! Is it possible to add path based authorisation to files served with
static { ... }
? What I would like to do: • user A can access files from
./a
folder • user B can access files from
./a
and
./b
folders Authentication is done in a very different part of the application. I wouldn't touch that if there is a way. Actually, I shouldn't touch that as authentication and authorisation are two different topics. As I see, my only option right now is to write (i.e. cut&paste from Ktor) my own handling of static resources and add the authorisation. Are there any better options? Thanks in advance.
a
I guess you could work with an interceptor using different paths?
Copy code
routing {
    route("/assets") {
        static {
            files("./a")
        }
        route("/protected") {
              intercept(ApplicationCallPipeline.Call) {
                    if (!call.user.isAllowedToAccessProtectedResources) return@intercept call.respond(HttpStatusCode.Forbidden)
                    proceed()
              }
              static {
                  files("./b")
              }
        }
    }
}
🙌 1
t
Good point, thank you. I had some fuzzy memory about having interceptors but a short look a the documentation did not reveal the details. Thanks for the example, I'll give it a try.
Tried it, it works, but
call.respond(...)
generates an error because there is a session cookie and the response is already closed when Ktor tries to add the cookie:
Copy code
2022-08-16 10:54:51.228 [eventLoopGroupProxy-4-1       ] ERROR ktor.application - 403 Forbidden: GET - /api/content/en/development/Todo.md
java.lang.UnsupportedOperationException: Headers can no longer be set because response was already completed
        at io.ktor.server.netty.http1.NettyHttp1ApplicationResponse$headers$1.engineAppendHeader(NettyHttp1ApplicationResponse.kt:42)
        at io.ktor.response.ResponseHeaders.append(ResponseHeaders.kt:47)
I replaced it with an unauthorized expression thrown and now it works quite OK. Thanks for the help.
a
That sounds like you need some kind of context.