How do I pass credentials to Sonar API calls?

2019-03-15 20:55发布

问题:

When I try to call:

https://sonar.mydomain.com/api/resources?resource=com.mydomain.project:MY&metrics=ncloc&format=json

I get

{"err_code":401,"err_msg":"Unauthorized"}

How do I pass my credentials?

回答1:

According to the documentation SonarQube uses basic authentication. Try:

curl -u admin:SuPeRsEcReT "https://sonar.mydomain.com/api/resources?resource=com.mydomain.project:MY&metrics=ncloc&format=json"

Obviously the mechanism for passing these credentials is dependent on how you are invoking the API.

This should also work from the web browser. Try logging into the Webui, your browser will normally cache the credentials.



回答2:

According to the newest documentation said: SonarQube now support two way authentication:

  • User Token

This is the recommended way. Token is sent via the login field of HTTP basic authentication, this way will be more safety, without any password. For more information about how to generate a token, please visit this page User Token. Use curl send request like this:

curl -u THIS_IS_MY_TOKEN: https://sonarqube.com/api/user_tokens/search
# note that the colon after the token is required in curl to set an empty password 
  • HTTP Basic Access

Login and password are sent via the standard HTTP Basic fields:

curl -u MY_LOGIN:MY_PASSWORD https://sonarqube.com/api/user_tokens/search


回答3:

This happens because authentication data does not include in your api call. This is how I solved it.

1.First install a rest client "Postman" to your browser.
2.Open it and put your API call url under "Normal" tab.
3.Go to "Basic Auth" tab and put username,password then click refresh headers.
4.Come back to "Normal" tab. You'll see a header named "Authorization" in header list.
5.Now click "send" button to view results.
6.If you are using 3rd party application, add "Authorization" header to your call with the value generated by postman.



标签: api sonarqube