https://kotlinlang.org logo
#ktor
Title
# ktor
u

Ulrich Winter

12/07/2023, 7:50 AM
Good morning. I'm having problems to get my custom plugin interact with the Authentication plugin: I need the response status code within a
on(ResponseBodyReadyForSend)
hook. I can get it from
call.response.status()
in most cases - but not, when authentication has failed. In that case, I get a
null
result. The actual
401
status code seems to be generated somewhere later in the plugin chain. My custom plugin is installed after the Authentication plugin. How can I retrieve the real status code which is sent to the client within my custom plugin?
1
a

Aleksei Tirman [JB]

12/07/2023, 8:42 AM
You can add a handler to the
ResponseSent
hook to observe the response status:
Copy code
val plugin = createApplicationPlugin("plugin") {
    on(ResponseSent) { call ->
        println("Intercepted status: ${call.response.status()}")
    }
}
u

Ulrich Winter

12/07/2023, 8:44 AM
my custom plugin needs to modify the response: It's purpose is to add a header containing a cryptographic signature over some properties of the response (including the response status). Where is the status code actually determined in case of a failed authentication?
a

Aleksei Tirman [JB]

12/07/2023, 8:45 AM
It's determined in the
AuthenticationHook
hook
Then you can use the following code to determine the status:
Copy code
on(ResponseBodyReadyForSend) { call, content ->
    if (content is UnauthorizedResponse) {
        println(content.status)
    }
}
u

Ulrich Winter

12/07/2023, 8:52 AM
Thanks - that worked!
2 Views