Vijjendra Vijjendra - 3 years ago 85
ASP.NET (C#) Question

(400) Bad Request : Get AccessToken of Salesforce

I am trying to fetch all the contacts from Salesforce via oauth in my application. I am getting The remote server returned an error: (400) Bad Request. when trying to get access token via API Token Url on my call back page. even When I have copy the URL and direct paste to the URL it is giving me correct data. but can't get the Access token.

I am using below method to Get Access token. Please experts suggest me where I am doing mistake. Same method is working fine for Google and LinkedIn.

public async Task<TokenResponse> GetAccessToken(string code,string tokenUrl,string consumerKey,string consumerSecretKey,string redirecturl)
{

string responseFromServer = "";
var webRequest = WebRequest.Create(tokenUrl);

const string queryStringFormat = @"code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code";
string contents = string.Format(queryStringFormat
, code
, consumerKey
, consumerSecretKey
, redirecturl);

webRequest.Method = "POST";
byte[] postcontentsArray = Encoding.UTF8.GetBytes(contents);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postcontentsArray.Length;
using (Stream requestStream = webRequest.GetRequestStream())
{
requestStream.Write(postcontentsArray, 0, postcontentsArray.Length);
requestStream.Close();
WebResponse response = webRequest.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
responseFromServer = reader.ReadToEnd();
reader.Close();
responseStream.Close();
response.Close();
}
}
}

}
return JsonConvert.DeserializeObject<TokenResponse>(responseFromServer);
}


Please help me to resolve this issue.

Answer Source

I'm connecting to Salesforce without issue, but am using HttpClient instead of WebRequest.

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                {"grant_type", "password"},
                {"client_id", _clientId},
                {"client_secret", _clientSecret},
                {"username", _userName},
                {"password", _password}
            }
                );

                using (var httpClient = new HttpClient())
                {
                    var message =
                        await httpClient.PostAsync(_authorizationUrl, content).ConfigureAwait(false);
                    var responseString = await message.Content.ReadAsStringAsync().ConfigureAwait(false);

                    var obj = JObject.Parse(responseString);

                    var oauthToken = (string)obj["access_token"];
                    var serviceUrl = (string)obj["instance_url"];
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download