authentication - 401 使用 HttpBuilder (Groovy) 未经授权访问 Github API

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

我写了一个 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 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"])

关于authentication - 401 使用 HttpBuilder (Groovy) 未经授权访问 Github API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646734/

相关文章:

java - Tomcat6 中的基本身份验证不适用于目录

android - 如何使用 NfcA 类读取 Mifare Classic 标签?

grails - Grails:将字符串(用户名)用作主键,但是使用ignorecase保存并获取ID字符串(用户名)吗?

java - 在java中使用Imgur API时出现401错误

ruby-on-rails - 门卫给出 401 Unauthorized

iphone - 如何使用 iOS 登录网站

authentication - 我应该将 PKCE 用于 OpenID Connect 与 native 桌面应用程序吗?

encoding - groovy 中多部分/表单数据的编码器功能

groovy - 测试使用 System.console() 的 Groovy 类

Android 到 Django - 总是显示 401