【问题标题】:Why is HTTPBuilder basic auth not working?为什么 HTTPBuilder 基本身份验证不起作用?
【发布时间】:2013-10-18 18:30:23
【问题描述】:

以下代码不对用户进行身份验证(不会发生身份验证失败,但由于权限不足导致调用失败):

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

为什么第一个不起作用?

【问题讨论】:

  • 它是如何失败的?服务器应返回 HTTP 401 状态代码以触发基本身份验证。然后 HttpBuilder 将发送带有 Authorization 标头的第二个请求。
  • 这行不通。请求本身返回一条消息,说明用户无权执行该操作。我可以将用户名和密码更改为完全无效的东西,同样的事情也会发生。
  • 这应该可以解决您的问题stackoverflow.com/questions/6588256/…

标签: groovy basic-authentication httpbuilder


【解决方案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
}

希望对你有帮助

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 在兼容的服务器上也会失败
    猜你喜欢
    • 2014-09-06
    • 2014-01-22
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 2016-11-17
    • 1970-01-01
    相关资源
    最近更新 更多