Search code examples
c#.netasp.net-web-apiaccess-tokenrestsharp

RestSharp unsupported grant type


Trying to query /token on my Web API using RestSharp.

In Fiddler I can compose the query and it executes no problem by: 1. Set Method to POST 2. Add a header: Content-Type: application/x-www-form-urlencoded 3. Set Body to: username=username&password=pass&grant_type=password

Trying to mimic this in RestSharp:

RestClient tokenClient = new RestClient();
tokenClient.BaseUrl = new Uri(GlobalSettings.WebApiTokenUrl);
RestRequest req = new RestRequest(Method.POST);
req.AddHeader("Content-Type", "application/x-www-form-urlencoded");

//req.Parameters.Add(new Parameter() { Name = "username", Value = User.Identity.Name, Type = ParameterType.RequestBody, ContentType= "application/x-www-form-urlencoded" });
//req.Parameters.Add(new Parameter() { Name = "password", Value = User.Identity.Name, Type = ParameterType.RequestBody, ContentType = "application/x-www-form-urlencoded" });
//req.Parameters.Add(new Parameter() { Name = "grant_type", Value = "password", Type = ParameterType.RequestBody, ContentType = "application/x-www-form-urlencoded" });
//req.Parameters.Add(new Parameter() { Name = "response_type", Value = "token", Type = ParameterType.RequestBody, ContentType = "application/x-www-form-urlencoded" });
req.AddParameter(new Parameter() { Name = "username", Value = User.Identity.Name, Type = ParameterType.RequestBody, ContentType = "application/x-www-form-urlencoded" });
req.AddParameter(new Parameter() { Name = "password", Value = User.Identity.Name, Type = ParameterType.RequestBody, ContentType = "application/x-www-form-urlencoded" });
req.AddParameter(new Parameter() { Name = "grant_type", Value = "password", Type = ParameterType.RequestBody, ContentType = "application/x-www-form-urlencoded" });
//req.AddParameter(new Parameter() { Name = "response_type", Value = "token", Type = ParameterType.RequestBody });


IRestResponse response = tokenClient.Execute(req);

var content = response.Content;
// I get: {"error":"unsupported_grant_type"}

Any ideas why this doesn't work? Also why is there a ContentType parameter in the Paramter object? I thought the ContentType should be set in the header? (I also tried removing ContentType from the parameter)

Thanks


Solution

  • See if this works.

         request.AddParameter("Content-Type", "application/x-www-form-urlencoded", ParameterType.HttpHeader);
         string encodedBody = string.Format("username={0}&password= {1}&grant_type={2}", User.Identity.Name, User.Identity.Name,password);
         request.AddParameter("application/x-www-form-urlencoded", encodedBody, ParameterType.RequestBody);
    

    Refer to this post. https://salesforce.stackexchange.com/questions/23295/unsupported-grant-type-error-when-trying-to-authenticate