【问题标题】:401 Unauthorized access for Github API using HttpBuilder (Groovy)401 使用 HttpBuilder (Groovy) 未经授权访问 Github API
【发布时间】:2013-07-15 04:22:11
【问题描述】:

我编写了一个 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
用户名:用户名
密码:
捕获:groovyx.net.http.HttpResponseException:未授权
groovyx.net.http.HttpResponseException: 未经授权
在 groovyx.net.http.HTTPBuilder.defaultFailureHandler(HTTPBuilder.java:652)
在 groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:508)
在 groovyx.net.http.HTTPBuilder.get(HTTPBuilder.java:292)
在 groovyx.net.http.HTTPBuilder.get(HTTPBuilder.java:262)
在 groovyx.net.http.HTTPBuilder$get.call(未知来源)
在 GithubHttpBuilderTest.run(GithubHttpBuilderTest.groovy:10)

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

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

输出:

[
“用户名@example.com”
]

我是否遗漏了有关如何使用 HttpBuilder 对 Github API 进行正确身份验证的内容?

编辑:修复了我的代码中的一个错误,我将System.console().readPassword 视为一个字符串,而不是它的实际返回类型:char[]。哎呀。

【问题讨论】:

    标签: authentication groovy http-status-code-401 github-api httpbuilder


    【解决方案1】:

    github.auth.basic username, password好像不行,需要手动设置:

    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"])
    

    【讨论】:

    • 谢谢。这是我的错误(实际上是 char[] 时将控制台中的密码视为字符串)和 github.auth.basic 似乎不起作用的事实的组合。它现在正在工作。谢谢!
    猜你喜欢
    • 2019-03-07
    • 2021-02-02
    • 2017-07-06
    • 2017-09-27
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多