Unable to access Web API (401 unauthorized)

hi All,
I was trying to access below web API(or any other sonarcloud API) to get data metrics for projects in my organization.
I created a token and tried to access the API through powershell which runs perfectly fine. however, when I try to use the same token and pass it as a Basic header using C# httpClient, I get 401 unauthorized error.
API call .
https://sonarcloud.io/api/project_branches/list?project=DevProject

Powershell Curl command (works for me)
curl -u xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: ‘https://sonarcloud.io/api/project_branches/list?project=DevProject

Appreciate any help!

Hi,

You need to append a colon to the token and base-64 encode it

e.g.

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        async static Task Main(string[] args)
        {
            var url = "https://sonarcloud.io/api/project_branches/list?project=DevProject";
            string token = "TODO - your token goes here";

            var client = new HttpClient
            {
                DefaultRequestHeaders =
                {
                    Authorization = GetBasicAuthTokenHeader(token)
                }
            };

            var response = await client.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Call succeeded:");
                var content = await response.Content.ReadAsStringAsync();
                Console.WriteLine(content);
            }
            else
            {
                Console.WriteLine("Call failed:");
                Console.WriteLine(response.ToString());
            }
        }

        private static AuthenticationHeaderValue GetBasicAuthTokenHeader(string token)
        {
            // The basic token needs to be base-64 encoded.
            // Also, it's expected to be in the form "username:password". If you are using a 
            // token you supply it in place of the username and leave the password blank i.e. "token:"
            var encodedToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(token + ":"));
            var authHeader = new AuthenticationHeaderValue("Basic", encodedToken);

            return authHeader;
        }
    }
}

Regards,
Duncan

1 Like