400 Bad Request when trying to get a Token using .NET (works using curl)

mrd777
Contributor
Contributor

I can get an auth token using cURL, but when I try to use .NET windows app, I get a "400 Bad request" with no further reasons as to why I can't get my code to work.

 

I know the client ID and key is right since I don't get an Authorization error (Unless I change the credentials, then I get an auth error)

 

Here is the code:

 

Dim strUpString As String = "grant_type=client_credentials"
Net.ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Tls12

Dim postReq As Net.HttpWebRequest = Net.HttpWebRequest.Create("https://api-m.paypal.com/v1/oauth2/token")
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(strUpString)
postReq.ContentLength = byteArray.Length
postReq.Method = "POST"
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.Headers.Add("Accept-Language", "en_US")
postReq.Headers.Add("Authorization", "<my-client-id>:<my-secret-key>")

postReq.Accept = "application/json"

Dim dataStream As Stream = postReq.GetRequestStream() 
dataStream.Write(byteArray, 0, byteArray.Length) 
dataStream.Close()

Dim response As Net.HttpWebResponse = postReq.GetResponse()

dataStream = response.GetResponseStream()

Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()

Login to Me Too
2 REPLIES 2

mrd777
Contributor
Contributor

Before anyone asks: Yes, I've tried URLEncoding the body data as well. No dice!

Login to Me Too

flyingkei
Contributor
Contributor

In your code, I noticed you're adding an Authorization header, but the Authorization header should be used once you have the token.

 

Instead , try adding an Authentication header. Set the Value to "Basic " + encodedAuthStr where encodedAuthStr is your "<my-client-id>:<my-secret-key>" encoded to Base64. 

 

I understand this is in a different language, but maybe my C# example will give you a little insight.

var authStr = $"{_options.ClientId}:{_options.ClientSecret}";
var encodedAuthStr = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(authStr));
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", encodedAuthStr);
Login to Me Too

Haven't Found your Answer?

It happens. Hit the "Login to Ask the community" button to create a question for the PayPal community.