身份验证 – 401使用HttpBuilder(Groovy)对Github API进行未经授权的访问

我写了一个Groovy脚本来管理
Github上的一些组织回购.几周前,当同一个脚本开始失败时,它工作得很好.也许Github改变了他们API的某些方面?或许我正在做一些愚蠢的事情.我已将问题缩小到这个简化的示例(需要有效的
github帐户):

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6' )

import groovyx.net.http.HTTPBuilder

String username = System.console().readLine 'Username: '
char[] password = System.console().readPassword 'Password: '

def github = new HTTPBuilder('https://api.github.com')
github.auth.basic username, password.toString()
def emails = github.get(path: '/user/emails', 
    headers: ['Accept': 'application/json', 'User-Agent': 'Apache HTTPClient'])
println emails

输出:

$groovy GithubHttpBuilderTest.groovy
Username: username
Password:
Caught: groovyx.net.http.HttpResponseException: Unauthorized
groovyx.net.http.HttpResponseException: Unauthorized
at groovyx.net.http.HTTPBuilder.defaultFailureHandler(HTTPBuilder.java:652)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:508)
at groovyx.net.http.HTTPBuilder.get(HTTPBuilder.java:292)
at groovyx.net.http.HTTPBuilder.get(HTTPBuilder.java:262)
at groovyx.net.http.HTTPBuilder$get.call(Unknown Source)
at GithubHttpBuilderTest.run(GithubHttpBuilderTest.groovy:10)

使用相同的凭据,curl工作:

$curl -u username https://api.github.com/user/emails

输出:

[
  “username@example.com”
]

我是否遗漏了如何使用HttpBuilder正确验证Github API?

EDIT: fixed an error in my code, where I treated System.console().readPassword as a String instead of its actual return type: char[]. Oops.

最佳答案 github.auth.basic用户名,密码似乎不起作用,您需要手动设置它:

String userPassBase64 = "$username:$password".toString().bytes.encodeBase64()    
def github = new HTTPBuilder('https://api.github.com')
def emails = github.get(path: '/user/emails', headers: ["Authorization": "Basic $userPassBase64"])
点赞