Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is HTTPBuilder basic auth not working?

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?

like image 831
Noel Yap Avatar asked Oct 18 '13 18:10

Noel Yap


1 Answers

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

like image 117
Lucas Crostarosa Avatar answered Nov 16 '22 02:11

Lucas Crostarosa