Why is HTTPBuilder basic auth not working?
Asked Answered
M

2

13

The following code doesn't authenticate the user (no authentication failure happens, but the call fails due to lack of permissions):

def remote = new HTTPBuilder("http://example.com")
remote.auth.basic('username', 'password')
remote.request(POST) { req ->
    uri.path = "/do-something"
    uri.query = ['with': "data"]

    response.success = { resp, json ->
        json ?: [:]
    }
}

But the following works fine:

def remote = new HTTPBuilder("http://example.com")
remote.request(POST) { req ->
    uri.path = "/do-something"
    uri.query = ['with': "data"]
    headers.'Authorization' = 
                "Basic ${"username:password".bytes.encodeBase64().toString()}"

    response.success = { resp, json ->
        json ?: [:]
    }
}

Why isn't the first one working?

Milkandwater answered 18/10, 2013 at 18:30 Comment(3)
How does it fail? The server should return an HTTP 401 status code to trigger the basic authentication. HttpBuilder will then send a second request with the Authorization header.Mangan
It just doesn't work. The request itself returns with a message saying the user doesn't have permissions to perform the operation. I can change the username and password to something completely invalid and the same thing happens.Milkandwater
This should potentially solve your problem #6588756Tyrr
H
1

Two things that I can think of off the top of my head.

The .setHeaders method requires a map. Have you tried
'Authorization' : "Basic ${"username:password".bytes.encodeBase64().toString()}" ?

If not, It's a bit more work and code, but you could user the URIBuilder as well. Generally I encapsulate to a different class

protected final runGetRequest(String endpointPassedIn, RESTClient Client){
      URIBuilder myEndpoint = new URIBuilder(new URI(Client.uri.toString() + endpointPassedIn))
      HttpResponseDecorator unprocessedResponse = Client.get(uri: myEndpoint) as HttpResponseDecorator
      def Response = unprocessedResponse.getData() as LazyMap
      return Response
}

Hope this helps

Howler answered 16/11, 2016 at 5:7 Comment(0)
E
0

Looks like your server isn't fully HTTPBuilder-compilant. It should return 401 code (which is standart behaviour for REST servers, but non-standart for others) for HTTPBuilder to catch this status and resend authentication request. Here is written about it.

Elevation answered 20/9, 2015 at 16:2 Comment(1)
It fails also on compliant serversFormat

© 2022 - 2024 — McMap. All rights reserved.