Logging into Salesforce with C# HttpClient
Asked Answered
R

1

2

I can't seem to get this code to work:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://login.salesforce.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
client.DefaultRequestHeaders.Add("User-Agent", "SFAPIClient"); //Random Client
var parameters = new Dictionary<string, string>();
parameters["grant_type"] = "password";
parameters["client_id"] = CLIENT_ID;
parameters["client_secret"] = CLIENT_SECRET;
parameters["username"] = t_username.Text;
parameters["password"] = t_password.Text;
var response = await client.PostAsync("https://login.salesforce.com/services/oath2/token", new FormUrlEncodedContent(parameters));
var responseString = await response.Content.ReadAsStringAsync();

Salesforce keeps responding with "this url no longer exists" which is what CURL was responding with before I got it working.

The CURL code I'm trying to mimic is:

curl [salesforce url] -d "grant_type=password" -d "client_id=[clientId]" -d "client_secret=[clientSecret]" -d "username=[username]" -d "password=[password]"

^ after running this the server responds with:

{"access_token":"[token]","instance_url":[etc...]}"

I'm hoping to get the same response in C# - it's been pretty annoying so far.

Rocco answered 3/9, 2019 at 21:12 Comment(7)
you said it was not working for curl and then it started working.. what did you change?Frankish
the endpoint for oauth seems to be incorrect. are you sure what you are using is fine... developer.salesforce.com/docs/atlas.en-us.api_rest.meta/…Frankish
@Frankish I was originally using the -X curl parameter before I think. I'm pretty sure that was what I changed.Rocco
@Frankish from your link: https://login.salesforce.com/services/oauth2/token - that's what I'm using and it's working just fine for curl. I tried it with an extra / and without.Rocco
can you try running this in postman or this [curl.olsh.me] to convert your code to c# and see if that works.Frankish
@Frankish the curl.olsh.me code gives me an SSL error when I try to run it. That seems to be remedied by adding ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; to the code.Rocco
Please see my edit for the curl output.Rocco
D
3

client.PostAsync("https://login.salesforce.com/services/oath2/token") has a typo - it should be oauth2, you're missing a letter.

Dore answered 4/9, 2019 at 2:44 Comment(2)
No way... if this is seriously the problem I'm going to facepalm so hard.Rocco
Dude OMFG I swear I looked at that URL 100 times... I cannot believe this. Thanks so much manRocco

© 2022 - 2024 — McMap. All rights reserved.