"unsupported_grant_type" error when trying to authenticate

  • 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?

  • 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.

    what are you sending in the first parameter 'code'?

    @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);`

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM