Search code examples
c#apirestdynatrace

401 (Unauthorized) when trying to access REST API


So basically, I am trying to connect to a REST API online. Easy enough right?

However I am getting a 401 (Unauthorized) error whenever I try to connect. I am using a C# console app to test this, and I have also tried using PUTMAN (Google Chrome App to view HTTP Requests).

Here is the link to the API I am using: https://community.dynatrace.com/community/display/APMSAASDOC/Login+-+REST+API

I follow all the steps listed. I know my username and password is correct (have logged into the Dynatrace Portal). Does anyone have any ideas what could be wrong? Here is my code below (I have removed the actual username and password for obvious reasons):

static async Task RunAsync()
    {
        string _user;
        string _password;
        string _authorizationType;
        string _contentType;
        string _CredentialsToBase64;
        string _url = "https://datafeed-api.dynatrace.com";

        _user = "MYUSERNAME";
        _password = "MYPASSWORD";
        _authorizationType = "basic";
        _contentType = "application/json";
        _CredentialsToBase64 = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(_user + ":" + _password));


        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(_url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_contentType));
            client.DefaultRequestHeaders.Add("Authorization", _authorizationType + " " + _CredentialsToBase64);

            using (HttpResponseMessage httpResponse = await client.GetAsync("publicapi/rest/v1.0/login?user=MYUSERNAME&password=MYPASSWORD HTTP/1.1"))
            {
                if (httpResponse.IsSuccessStatusCode)
                {
                    Console.WriteLine("Success");
                }
                else
                {
                    Console.WriteLine(string.Format("Service request failed ({0})", httpResponse.StatusCode));
                }
            }



        }

Solution

  • Sorry for the headache everyone. The problem was an account issue with the company itself. I contacted them and they noticed the problem was with a migration of accounts from a old to new portal. So there was nothing wrong with our end. Thanks for your help everyone!