Sonar REST api call from Jenkins pipeline

Hi,

I’m trying to make an sonarqube rest api call from jenkins pipeline script. However it is failing with 401 (Unauthorized) error if I use groovy URL(url).openConnection() module, but it works with curl.

sample snippet

node {
withSonarQubeEnv(sonar.env) {
def sonarUrl = env.SONAR_HOST_URL
def sonarAuthToken = env.SONAR_AUTH_TOKEN

*def query = “{sonarUrl}/api/issues/search?componentKeys={sonar.projId}&branch={sonar.projBranch}&statuses=OPEN,REOPENED,CLOSED&pageSize={pageSize}&pageIndex=${pageIndex}” *

def conn = new URL(query).openConnection();
conn.setRequestProperty(‘Accept’, ‘application/json’)
conn.setRequestProperty(“Authorization”, “Basic ${sonarAuthToken }” )
conn.setConnectTimeout(10000)

def getRC = conn.getResponseCode();

if(getRC.equals(200)) {
println(“I’m good”)
} else {
error “Query: {query}\nResCode: {conn.responseCode}\nResMsg: ${conn.responseMessage}”
}

}
}

But with curl it works fine

node {
withSonarQubeEnv(sonar.env) {
def sonarUrl = env.SONAR_HOST_URL
def sonarAuthToken = env.SONAR_AUTH_TOKEN

*def query = “{sonarUrl}/api/issues/search?componentKeys={sonar.projId}&branch={sonar.projBranch}&statuses=OPEN,REOPENED,CLOSED&pageSize={pageSize}&pageIndex=${pageIndex}” *

sh “curl {query} -v -u {sonarAuthToken}”
}
}

Any idea how I can get it working with URL(url).openConnection()?

I’m using “SonarQube Scanner for Jenkins” plugin version 2.8.1

Hi,
is your sonarAuthToken base64 encoded, and does it end with the separator : ?
Here is my groovy snippet for such cases and it works fine:

import groovy.json.*

def sonarRest(url,method) {
  jsonSlurper = new JsonSlurper()
  raw = 'your u s e r t o k e n:'
  bauth = 'Basic ' + javax.xml.bind.DatatypeConverter.printBase64Binary(raw.getBytes())
  conn = new URL(url).openConnection() as HttpURLConnection
  conn.setRequestMethod(method)
  conn.setRequestProperty("Authorization", bauth)
  conn.connect()
  httpstatus = conn.responseCode
  object = jsonSlurper.parse(conn.content)
}

Regards,
Gilbert

1 Like

Actually sonarAuthToken is nothing but env.SONAR_AUTH_TOKEN which is already set in withSonarQubeEnv block along with below sonar env’s

SONARQUBE_SCANNER_PARAMS={ "sonar.host.url" : "http:\/\/localhost:9000", "sonar.login" : "******"}
SONAR_HOST_URL=http://localhost:9000
SONAR_AUTH_TOKEN=******
SONAR_CONFIG_NAME=sonarqube_prd
SONAR_MAVEN_GOAL=sonar:sonar

Hi,

seems like the base64 encoding is handled by curl and the Sonarqube Jenkins plugin internally.
If you use it with Groovy you have to do it yourself.

Regards,
Gilbert

1 Like

Thanks for the pointer, will give it a try.