I’m having trouble with HTTPBuilder in Groovy when trying to authenticate with an API that doesn’t follow standard HTTP auth patterns.
The problem is that when an API endpoint doesn’t return a proper 401 Unauthorized response, HTTPBuilder won’t attempt authentication automatically. Since there are no “Authentication required” headers being sent back, the library just skips the auth step entirely.
I found a workaround by manually setting the Authorization header before making requests:
def username = 'john'
def password = 'mypass123'
def client = new HTTPBuilder('http://api.example.com')
client.headers['Authorization'] = "Basic " + "$username:$password".getBytes('iso-8859-1').encodeBase64()
This approach forces authentication on every request regardless of the server response. It works but feels like a workaround rather than a proper solution.
Is there a cleaner way to handle this situation? Are there any HTTPBuilder settings I might be missing that could make this work more elegantly?
I experienced a similar issue with an older REST service that had non-standard authentication practices. Your method of manually configuring the Authorization header is a solid solution and commonly used in many production environments.
Another option is to utilize auth.basic() directly within your requests instead of setting a global header. This can provide finer control over authentication:
def client = new HTTPBuilder('http://api.example.com')
client.request(GET, JSON) {
auth.basic 'john', 'mypass123'
// your request logic here
}
This approach manages authentication for each individual request, aligning better with APIs that do not conform to RFC standards.
your workaround’s pretty standard for these janky APIs. I’ve hit this exact issue with legacy systems that won’t send proper auth headers. try setting client.auth.basic username, password right after creating the httpclient - sometimes that forces preemptive auth headers instead of waiting for the 401.
Hit this exact issue with some internal corporate APIs migrated from legacy systems. Your preemptive auth approach is actually best practice for these non-compliant endpoints. I’d suggest setting up a custom request interceptor that automatically adds the Basic auth header. You can configure it as a default for all requests so you don’t have to manually build the base64 encoding every time. Keeps your auth logic in one place and makes maintenance easier. Truth is, lots of enterprise APIs don’t follow HTTP auth standards properly - especially legacy stuff. Your solution works great since it skips the round-trip overhead from challenge-response cycles.