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

Sam

03/31/2023, 1:37 AM
I'm reading up on how Bearer auth works with Ktor client. Am I correct that, notwithstanding a
sendWithoutRequest
block, it looks for a 401 response with a
WWW-Authenticate
header with a matching
realm
and then sends that token? Is there any way to short-circuit or restrict that?
a

Aleksei Tirman [JB]

03/31/2023, 4:03 AM
If the
sendWithoutRequest
returns
true
an initial request contains the
Authorization
header with the Bearer token.
s

Sam

03/31/2023, 4:04 AM
Right, but otherwise it looks for that header and sends the matching token right?
I'm asking because I'm wondering if that means that it's a good practice to construct a separate client for each domain you make requests to. Otherwise a compromised domain could just... send a response with a header asking for a token that's not theirs and the client would just... send it.
a

Aleksei Tirman [JB]

03/31/2023, 4:06 AM
Yes, and calls the
refreshTokens
block to obtain new tokens.
Can you please give an example?
s

Sam

03/31/2023, 4:10 AM
Like, imagine I have a single client that I use to make requests to Domain A and Domain B, and I have
bearer
auth configured for each domain with its own
realm
. If Domain B were compromised they could send a malicious
WWW-Authenticate
header containing A's
realm
and the client would automatically send them my token for A. Basically, there's no way to say "apply this auth provider to ONLY these requests". You can tell it to eagerly send for certain requests, but it always falls back on that header.
This is just hypothetical. Right now I'm only making requests to our own servers. The behavior just struck me as odd.
And made me wonder if the intent is for a different
HttpClient
to be constructed for each domain
Right now I just make a single client in Koin and share it everywhere
a

Aleksei Tirman [JB]

03/31/2023, 4:16 AM
Right. If you have such a concern, creating a separate client for each domain or manually sending the
Authorization
header would be the solution.
s

Sam

03/31/2023, 4:19 AM
Fair enough!
It would be nice to have a
sendIf
or the like to provide a fully custom behavior, but this was just a hypothetical anyway. Thanks for the chat!
r

Rustam Siniukov

03/31/2023, 8:09 AM
sendWithoutRequest
accepts
HttpRequestBuilder
, you can check which domain the request is made to
s

Sam

03/31/2023, 1:35 PM
Right, but if you return false from that block it will still send the token in response to a 401
r

Rustam Siniukov

03/31/2023, 1:44 PM
only if
realm
matches (or null)
s

Sam

03/31/2023, 2:59 PM
Right, that's what prompted my question. I'd prefer if I could configure it to send ONLY if the block returns true.
175 Views