Skip to content

Authentication, TLS, and Proxy

Contents | Previous: Handling Responses | Next: Streaming

After reading this chapter

This chapter distinguishes credentials, certificates, and proxy builder options. The Basic authentication example comes from each language's HttpClient tutorial.

Authentication and transport security are selected while creating a client. TLS encrypts transport to an HTTPS target and validates its server certificate. mTLS also validates a client certificate. A proxy relays the client's HTTP requests to the target API. A request-specific authentication header overrides client configuration when credentials differ for one request.

This tutorial uses plain HTTP

TLS, mTLS, and proxy options belong to the deployed endpoint. The tutorial code omits them.

↗ 크게 보기

Target credentials attach to the request header, while proxy credentials attach only to the proxy leg. Certificate validation and mTLS apply to the TLS leg for both a direct connection and a CONNECT tunnel.

1. Basic and Bearer Authentication

basicAuth creates an Authorization: Basic header from a user and password. bearerToken creates an Authorization: Bearer header from a token. A request-specific Authorization header takes precedence over this client configuration.

val unauthenticated = zlinkHttpClient("http://127.0.0.1:5381") {}
val authenticated =
    zlinkHttpClient("http://127.0.0.1:5381") { basicAuth("ops", "tutorial-admin") }
try {
    val without =
        unauthenticated
            .post("/admin/channels/profile/weight")
            .query("value", "2")
            .awaitRaw()
    val with =
        authenticated.post("/admin/channels/profile/weight").query("value", "2").awaitRaw()
    println("basic auth: without ${without.status} with ${with.status}")
} finally {
    unauthenticated.close()
    authenticated.close()
}

The example contrasts a 401 response without credentials with a 200 response from the same path using Basic authentication.

2. Trusted Certificates

trustCertificateFile adds a PEM certificate to the system trust store. It validates a private CA or self-signed server without replacing system roots. No option disables hostname validation.

3. An mTLS Client Certificate

clientCertificateFile configures a PEM client certificate and a PKCS#8 key. It applies to an HTTPS endpoint that requires client authentication.

4. An HTTP Proxy

proxy accepts an http:// proxy URL only. For an HTTPS target, the client opens a CONNECT tunnel through the proxy and performs TLS inside it, so the proxy cannot read the target request content. proxyBasicAuth sends Basic credentials only to the proxy, never to the target server.

5. Next Chapter

Streaming covers paths that send or receive a large body without accumulating it.