I’m using SonarQube Docker image sonarqube
and .NET WebClient
.
There I can login with the API api/authentication/login
with a Form request (POST
with UploadString
) and values login=admin&password=admin
. Get an empty string as response and response code is 200.
After this I’m picking the Cookies XSRF-TOKEN
and JWT-SESSION
from response headers and put them in the Cookie
header for next request.
A next request to api/webservices/list
(GET
with DownloadString
) happens well, get a JSON response with the whole list.
When I try the API request api/users/change_password
with a Form request (POST
with UploadString
) and values login=admin&password=adminNew&previousPassword=admin
, then I receive a HTTP exception with status 401 (Unauthorized).
Same happens when I try api/projects/create
(POST
with UploadString
) and values project=TEST&name=Test
.
When I use the Web UI to create a project there manually. then I can access the api/project_branches/list
with QueryString
value project=TEST
and get a JSON response also.
Why can’t I use the API POST
endpoints, but those with the GET
?
Code sample
const String API_URL = "http://localhost:9000/api";
WebClient webClient = new WebClient();
String response;
String cookies;
webClient.Headers
.Set(HttpRequestHeader.ContentType,
"application/x-www-form-urlencoded");
response = webClient.UploadString($"{API_URL}/authentication/login",
"login=admin&password=admin");
Console.WriteLine($"Login response := \"{response}\"");
Console.WriteLine();
// Take over (session) cookies
cookies = String.Join("; ",
webClient.ResponseHeaders[HttpResponseHeader.SetCookie]
.Split(',')
.Select(cookie => cookie.Split(';')[0]));
webClient.Headers
.Set(HttpRequestHeader.Cookie,
cookies);
// This works well, when authenticated
response = webClient.DownloadString($"{API_URL}/webservices/list");
Console.WriteLine($"WebServices response := \"{response}\"");
Console.WriteLine();
webClient.Headers
.Set(HttpRequestHeader.Cookie,
cookies);
// This also
response = webClient.DownloadString($"{API_URL}/user_tokens/search");
Console.WriteLine($"User tokens response := \"{response}\"");
Console.WriteLine();
webClient.Headers
.Set(HttpRequestHeader.Cookie,
cookies);
webClient.Headers
.Set(HttpRequestHeader.ContentType,
"application/x-www-form-urlencoded");
// This fails, but it's authenticated
response = webClient.UploadString($"{API_URL}/users/change_password",
"login=admin&password=adminNew&previousPassword=admin");
Console.WriteLine($"Change password response := \"{response}\"");
BTW: When inheriting the WebClIent
it’s possible to àttach a CookieContainer
also and the request header handling for Cookie
is not required.