RestSharp不支持的授权类型

时间:2017-04-21 16:05:29

标签: c# .net asp.net-web-api access-token restsharp

尝试使用RestSharp在我的Web API上查询/token

在Fiddler中我可以编写查询,它执行没有问题: 1.将方法设置为POST 2.添加标题:Content-Type: application/x-www-form-urlencoded 3.将Body设置为:username = username& password = pass& grant_type = password

试图在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"}

为什么这不起作用的任何想法? 另外,为什么Paramter对象中有ContentType参数?我以为应该在标题中设置ContentType? (我也尝试从参数中删除ContentType)

由于

1 个答案:

答案 0 :(得分:1)

看看是否有效。

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

参考这篇文章。 https://salesforce.stackexchange.com/questions/23295/unsupported-grant-type-error-when-trying-to-authenticate