API resquests not working

  • Enterprise Edition Version 9.9 (build 65466)
  • Zip

Hello, we have had a PowerShell script that we have been running for a couple of years with a token that is set to not expire. A few months ago it stopped working, I have been trying to troubleshoot the issue and I am getting 401’s when trying to do project search or valid user calls.

Our script uses Invoke-Webrequest with Authorization header and the token converted to base 64. We haven’t changed the script or revoked the token.

What I have done to troubleshoot.

  1. Created new token and verified user is with our Sonar Admin group with has administer permission to all projects. Verified with a few projects and permissions are there.
  2. Replicated API Request on postman with old token and newly generated token. Same outcome 401.
  3. Used the built-in admin basic username and password authentication with postman. This works.
  4. Tried to use bearer token in postman with and without base 64 encoding, same 401.

It seems that tokens do not work and only method is Basic username and password with the built-in admin. Our users and admins use single sign on and Tokens do not seem to work anymore. We had this working for few years, I checked documentation to see of any major changes and I do not see anything that stands out.

Hey there.

I would suggest including an example script that’s not working, that was working before.

Here is the code. As mentioned I have created new tokens, also tested new tokens with Postman and still doesn’t work.

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$baseURL = "https://sonar.ourcompany.com"
#Get token from encrypted xml file
$token = Import-CliXml -Path  "D:\Encrypted\sonaradmintoken.xml"
$sonarAuthToken = $token.GetNetworkCredential().Password

#Convert token to base64 (Required)
$gettokenBytes = [System.Text.Encoding]::UTF8.GetBytes("$($sonarAuthToken)" + ":")
$convertTobase64 = [System.Convert]::ToBase64String($gettokenBytes)
$authToken = [string]::Format("Basic {0}", $convertTobase64)

$arrayofprojectKeys = @()
#Initialize an array of metric values to be captured
$arrayofMetricObjects = @()

#List of Metric Definitions can be found here https://docs.sonarqube.org/latest/user-guide/metric-definitions
#To add more metrics, retreive the name of the metric you want from the above link and insert into the below array.
$arrMetricKeys = @(
    "reliability_rating",
    "security_rating",
    "security_review_rating",
    "sqale_rating"   
)
$strMetricKeys = $arrMetricKeys -join ","

$getProjectsUri = "$baseURL/api/projects/search"
#Send web request to SonarQube to get project keys
#Create response headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept","application/json")
$headers.Add("Content-Type", "application/json")
$headers.Add("Authorization", $authToken)


try {
    #Make Web Request
    $getProjectsResponse = Invoke-WebRequest $getProjectsUri -Method 'GET' -Headers $headers

    if ($getProjectsResponse.StatusCode -eq 200){
        #Load project keys into array
        $projects = $getProjectsResponse.Content | ConvertFrom-JSON
        for ($i = 0;$i -lt $projects.components.length;$i++) {
            $arrayofprojectKeys += $projects.components[$i].key
          
        }
        
    }

    #Get metrics from each project in the array $arrayofprojectKeys
    foreach ($proj in $arrayofprojectKeys) {
        $getMetricsUri = [string]::Format("{0}/api/measures/component?component={1}&metricKeys={2}", $baseURL, $proj, $strMetricKeys)
        $getMetricsResponse = Invoke-WebRequest $getMetricsUri -Method 'GET' -Headers $headers

        if ($getMetricsResponse.StatusCode -eq 200){
            #Load metrics into array
            $jsonObj = $getMetricsResponse.content
            $arrayofMetricObjects += $jsonObj
            
        }

    }  
    $arrayofMetricObjects = $arrayofMetricObjects -join ","
    $date = (get-date).ToString("_yyyy-MM-dd")
    "{""sonarmetrics"":[" + $arrayofMetricObjects +"]}" | Out-File "\\server\SonarQube\sonarqubemetrics$date.json" -Encoding utf8 -Force
    
}
catch {
    Write-Host "An error occurred when retrieving metrics:" $_ -ForegroundColor Red
    
}



Thanks.

I’m surprised to hear that the Token isn’t working, even in postman.

How are you providing the token in Postman? Here, I’m providing it in the “Username” field of Basic Auth