2013-10-18 47 views
12

下面的代码不验证用户(无身份验证失败情况发生,但调用失败,由于缺乏权限):为什么HTTPBuilder基本身份验证不起作用?

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 ?: [:] 
    } 
} 

但以下工作正常:

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 ?: [:] 
    } 
} 

为什么ISN第一个工作吗?

+2

它是如何失败?服务器应该返回一个HTTP 401状态码来触发基本认证。然后HttpBuilder将发送第二个请求和授权标头。 – ataylor

+0

它只是不起作用。请求本身会返回一条消息,指出用户没有执行该操作的权限。我可以将用户名和密码更改为完全无效的内容,并发生相同的情况。 –

+2

这应该有可能解决您的问题 http://stackoverflow.com/questions/6588256/using-groovy-http-builder-in-preemptive-mode –

回答

0

看起来你的服务器并不完全是HTTPBuilder编译器。它应该返回401代码(这是REST服务器的标准行为,但对于其他标准不是标准行为),以便HTTPBuilder捕获此状态并重新发送认证请求。 Here是关于它的。

1

我能想到的两件事情就是从我头顶开始。

.setHeaders方法需要一张地图。你有没有试过
'Authorization' : "Basic ${"username:password".bytes.encodeBase64().toString()}"

如果不是,这是一个更多的工作和代码,但你也可以使用URIBuilder。一般来说,我封装到一个不同的类

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 
} 

希望这有助于

相关问题