Search code examples
c#asp.netaccess-tokendotnet-httpclient

Why an error is created when creating the token


 public static void CreateToken()
    {

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("grant_type", "client_credentials");
        var UserPassJson = "{\"username\": \"mucode\",\"password\": \"mypassword\"}";

        HttpContent content = new StringContent(UserPassJson, Encoding.UTF8, "application/json");

        var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v1/oauth2/token"), content).Result;
        if (response.IsSuccessStatusCode)
        {
            var responseContent = response.Content;
            string responseString = responseContent.ReadAsStringAsync().Result;
            Console.WriteLine(responseString);
        }
    }

Why response.IsSuccessStatusCode Showing status code 401? What causes the malfunction? What action does cause success?


Solution

  • The documentation specifies that you should pass the username and password using basic authentication and that you should pass a form-encoded body containing grant_type=client_credentials.

    At the moment your code adds grant_type as a header, and posts the username and password as a JSON object in the body.

    Correcting your code to do it the way the documentation says, we get:

    HttpClient client = new HttpClient();
    byte[] authBytes = System.Text.Encoding.ASCII.GetBytes("mucode:mypassword");
    string base64Auth = Convert.ToBase64String(authBytes);
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64Auth);
    
    HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("grant_type", "client_credentials") });
    
    var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v1/oauth2/token"), content).Result;
    if (response.IsSuccessStatusCode)
    {
        var responseContent = response.Content;
        string responseString = responseContent.ReadAsStringAsync().Result;
        Console.WriteLine(responseString);
    }
    

    P.S. I recommend reading You're using HttpClient wrong and it is destabilizing your software and the follow-up You're (probably still) using HttpClient wrong and it is destabilizing your software. I also recommend making this method async and making the chain all the way up async too.