1

I am using the following code to try to get an authenticate. This is in C#, using the RestSharp library:

public string GetAuthToken(string code)
{
    var client = new RestClient("https://login.salesforce.com/services/oauth2/token");
    var request = new RestRequest(Method.POST);
    string body = string.Format("code={0}&grant_type=authorization_code&client_id={1}&client_secret={2}&redirect_uri={3}",
        code, Constants.SF.OAuth_ConsumerKey, Constants.SF.OAuth_ConsumerSecret, Constants.SF.OAuth_CallbackUrl);
    request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
    request.AddBody(body);
    var response = client.Execute(request);
    return response.Content;
}

When I run this, I always get the following response:

{
  "error_description":"grant type not supported",
  "error":"unsupported_grant_type"
}

Where am I going wrong?

1 Answer 1

4

Looking at the request in Fiddler, I noticed that the headers and body that I set using RestSharp with the code above were not being set.

After some experimentation and research, the following code ended up working:

public AuthToken GetAuthToken(string code)
{
    var client = new RestClient("https://login.salesforce.com/services/oauth2/token");
    var request = new RestRequest(Method.POST);
    string encodedBody = string.Format("code={0}&grant_type=authorization_code&client_id={1}&client_secret={2}&redirect_uri={3}",
        code, Constants.SF.OAuth_ConsumerKey, Constants.SF.OAuth_ConsumerSecret, Constants.SF.OAuth_CallbackUrl);
    request.AddParameter("application/x-www-form-urlencoded", encodedBody, ParameterType.RequestBody);
    request.AddParameter("Content-Type", "application/x-www-form-urlencoded", ParameterType.HttpHeader);
    var response = client.Execute<AuthToken>(request);
    return response.Data;
}

For some reason, RestSharp only set the body and headers properly when using the AddParameter method. Setting this, and being sure to use "application/x-www-form-urlencoded" as the content type and body type allowed this to work.

2
  • 1
    what are you sending in the first parameter 'code'? Jul 8, 2015 at 20:42
  • @MehulJoisar you don't need the parameter code. I am using grant_type=password and so far this is the only method that works for me. I am using postman and it works but unable to do the same using the normal AddParameter in RestSharp. So following Yaakov's code all I did was change my body to this and it works string encodedBody = string.Format("grant_type=password&client_id={0}&client_secret={1}&username={2}&password={3}", client_Id, client_secret, username, password);
    – CB4
    Aug 14, 2019 at 16:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .