Search code examples
groovyauthorizationgithub-apigithub-enterprisegithub-api-v3

How to add authentication to URL() or JsonSlurper()


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()?


Solution

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