2

I have a groovy script that closes old pull requests. The part where it fetches the open pull requests worked before with an access token:

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)

We migrated from Gitea to GitHub Enterprise and now I need to use the User Header field for authorization. This is how it works with 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" 

I have tried:

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)

and

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)

but I'm always getting a 401 - Unauthorized. What's the correct way to add authorization to URL() or JsonSlurper()?

mles
  • 4,534
  • 10
  • 54
  • 94
  • 1
    Are you sure that this is correct: `getBytes('iso-8859-1')`? Could you try with `getBytes('UTF-8')`? – Andrej Istomin Jun 07 '22 at 13:37
  • I'm not sure about my code at all as I'm not a groovy expert ;) I tried it with `UTF-8`, but I'm also getting a 401. – mles Jun 07 '22 at 19:17

1 Answers1

0

I got the base64 encoding wrong. This is how it works:

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]
        )
mles
  • 4,534
  • 10
  • 54
  • 94