I want to add basic auth headers in some tests, bu...
# http4k
d
I want to add basic auth headers in some tests, but not others. I can use postfix withBasicAuth
Copy code
val request = Request(GET, "/items?date=2021-01-02")
            .withBasicAuth(Credentials("testUser", "testUser-pass"), "Authorization")
but is there a way to do the same without specifying the header name?
d
can you expand a bit on this?
d
It looks like the ClientFilters.BasicAuth is used to decorate a client? I don’t want to decorate the client, but populate the request.
CustomBasicAuth has Request.withBasicAuth(creds, header), which is what I’m using there ^^. Am I missing a way to do the same with the other ClientFilters?
I’ve written `
Copy code
private fun Request.withBasicAuth(credentials: Credentials) = withBasicAuth(credentials, "Authorization")
which does the job, but I want to be as vanilla as possible
d
so you want a generic postfix method for adding a header? that's just
Request.header()
isn't it?
d
Not just any old header, I want a generic postfix method for encoding and adding the Authorization header
d
isn't the header name always Authorization?
a
I think Duncan might be looking for something like a
BiDiLens<Request, Credentials>
for basic auth. I don't think it exists, but I can think of several uses for it.
d
That’s certainly the sort of thing! In the meantime, https://github.com/http4k/http4k/commit/02d38f8e94802a1b46349a180816a0d5b2be16b2 has done the job thanks @dave
a
Oh I had no idea that existed.
d
that makes 2 of us (before Duncan told me about it! 😂 )
a
A lens would still be useful. I just had to write this monstrosity yesterday.
Copy code
val (headerClientId, headerClientSecret) = request.header("Authorization")
                ?.trim()
                ?.takeIf { it.startsWith("Basic") }
                ?.substringAfter("Basic")
                ?.trim()
                ?.base64Decoded()
                ?.split(":", ignoreCase = false, limit = 2)
                .let { parts ->
                    val clientId = parts?.getOrNull(0)?.let(::ClientId)
                    val clientSecret = parts?.getOrNull(1)?.let(::ClientSecret)
                    clientId to clientSecret
                }
It's on my todo list, along with improvements to the BasicAuth ServerFilter and Security to accept a lookup rather than a single set of credentials.
@dmcg if you still have need for the BiDi lens mapping, it's coming in the next release
d
which is now in maven central.... 4.32.2.0 🙂
d
Thank you both. It may be too late for the Jax London session codebase, but watch out for the video
146 Views