groovy 如何向URL()或JsonSlurper()添加身份验证

nszi6y05  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(268)

我有一个groovy脚本,它可以关闭旧的pull请求。它获取打开的pull请求的部分以前使用访问令牌工作过:

String json = new URL("${giteaUrl}/api/v1/repos/projectname/reponame/pulls?page=${page}&state=all" +
        "&sort=recentupdate&access_token=${accessToken}").getText()
prData = new JsonSlurper().parse(json.bytes)

我们从Gitea迁移到了GitHub Enterprise,现在我需要使用User Header字段进行授权。下面是curl的工作方式:

curl  \
  -s   \
  -f  \
  --user "username:apitoken" \
  --header 'Accept: application/vnd.github.v3+json' \
  --header 'Content-Type: application/json' \
  --request GET "https://repourl.com/api/v3/repos/projectname/reponame/pulls"

我试过:

String json = new URL("${gitUrl}/api/v3/repos/projectname/reponame/pulls?page=${page}&state=all" +
        "&sort=recentupdate").getText(
            requestProperties: ["User": "${gitApiUser}:${gitApiToken}"]
        )
prData = new JsonSlurper().parse(json.bytes)

String json = new URL("${gitUrl}/api/v3/repos/projectname/reponame/pulls?page=${page}&state=all" +
        "&sort=recentupdate").getText(
            requestProperties: ["Authorization": +
              "Basic " + "${gitApiUser}:${gitApiToken}".getBytes('iso-8859-1').encodeBase64() ]
        )
prData = new JsonSlurper().parse(json.bytes)

但我总是得到401 - Unauthorized。向URL()或JsonSlurper()添加授权的正确方法是什么?

nhaq1z21

nhaq1z211#

我把base64编码弄错了。它是这样工作的:

def authorizationString = 
    (System.getenv('GIT_API_USER') + ':' + System.getenv('GIT_API_PASSWORD'))
    .bytes.encodeBase64().toString()

String json = new URL("${gitcUrl}/api/v3/repos/PC/pc_releases/pulls" + 
        "?page=${page}&state=all&sort=recentupdate").getText(
            requestProperties: ['Authorization': 'Basic ' + authorizationString]
        )

相关问题