调用Web API时出现C#不支持的授权类型

72

我正在尝试从C# WPF桌面应用程序向我的WebAPI执行Post操作。

无论我做什么,我都会得到:

{"error":"unsupported_grant_type"}

这是我尝试过的(我已经尝试了一切可找到的方法):

同时,Dev Web API目前处于测试状态:http://studiodev.biz/

base http client object:

var client = new HttpClient()
client.BaseAddress = new Uri("http://studiodev.biz/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));

使用以下发送方法:

var response = await client.PostAsJsonAsync("token", "{'grant_type'='password'&'username'='username'&'password'='password'");
var response = await client.PostAsJsonAsync("token", "grant_type=password&username=username&password=password");

失败后,我进行了一些谷歌搜索并尝试了以下方法:

LoginModel data = new LoginModel(username, password);
string json = JsonConvert.SerializeObject(data);
await client.PostAsync("token", new JsonContent(json));

同样的结果,所以我尝试了:

req.Content = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded");
await client.SendAsync(req).ContinueWith(respTask =>
{
 Application.Current.Dispatcher.Invoke(new Action(() => { label.Content = respTask.Result.ToString(); }));
});

注意:我能够使用Chrome成功调用。

更新Fiddler结果

enter image description here

请问是否有人可以帮忙成功调用上述的Web API... 如果需要澄清,请告诉我。 感谢!


你尝试过使用 Fiddler 来定位 Chrome 调用和 WPF 应用程序调用之间的差异吗? - RagtimeWilly
我有,请查看更新。我已经尝试了所有方法来复制结果。请帮忙。 - OverMars
8个回答

162

OAuthAuthorizationServerHandler 的默认实现只接受表单编码(即 application/x-www-form-urlencoded),而不接受 JSON 编码(application/JSON)。

您的请求的ContentType 应为 application/x-www-form-urlencoded,并将数据作为正文传递:

grant_type=password&username=Alice&password=password123

即不是JSON格式。

上面的Chrome示例之所以有效,是因为它没有传递数据作为JSON。 你只需要这个来获取一个token;对于API的其他方法,你可以使用JSON。

这种问题也在这里讨论过。


2
非常感谢!我卡了三天了。 - OverMars

17

1)请注意URL:“localhost:55828/token”(而不是“localhost:55828/API/token”)

2)请注意请求数据。它不是json格式,只是没有双引号的普通数据。 “userName=xxx@gmail.com&password=Test123$&grant_type=password”

3)请注意内容类型。Content-Type:'application/x-www-form-urlencoded'(而不是Content-Type:'application/json')

4)当您使用JavaScript进行POST请求时,可以使用以下内容:

$http.post("localhost:55828/token", 
    "userName=" + encodeURIComponent(email) +
        "&password=" + encodeURIComponent(password) +
        "&grant_type=password",
    {headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
).success(function (data) {//...

请查看下面来自Postman的截图:

Postman请求

Postman请求头


15

这是一个我用来请求本地Web API应用程序的工作示例,它在端口43305上使用SSL运行。我也将该项目放在GitHub上。 https://github.com/casmer/WebAPI-getauthtoken

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http;
using System.Web;

namespace GetAccessTokenSample
{
  class Program
  {
    private static string baseUrl = "https://localhost:44305";

    static void Main(string[] args)
    {

      Console.WriteLine("Enter Username: ");
      string username= Console.ReadLine();
      Console.WriteLine("Enter Password: ");
      string password = Console.ReadLine();

      LoginTokenResult accessToken = GetLoginToken(username,password);
      if (accessToken.AccessToken != null)
      {
        Console.WriteLine(accessToken);
      }
      else
      {
        Console.WriteLine("Error Occurred:{0}, {1}", accessToken.Error, accessToken.ErrorDescription);
      }

    }


    private static LoginTokenResult GetLoginToken(string username, string password)
    {

      HttpClient client = new HttpClient();
      client.BaseAddress = new Uri(baseUrl);
      //TokenRequestViewModel tokenRequest = new TokenRequestViewModel() { 
      //password=userInfo.Password, username=userInfo.UserName};
      HttpResponseMessage response =
        client.PostAsync("Token",
          new StringContent(string.Format("grant_type=password&username={0}&password={1}",
            HttpUtility.UrlEncode(username),
            HttpUtility.UrlEncode(password)), Encoding.UTF8,
            "application/x-www-form-urlencoded")).Result;

      string resultJSON = response.Content.ReadAsStringAsync().Result;
      LoginTokenResult result = JsonConvert.DeserializeObject<LoginTokenResult>(resultJSON);

      return result;
    }

    public class LoginTokenResult
    {
      public override string ToString()
      {
        return AccessToken;
      }

      [JsonProperty(PropertyName = "access_token")]
      public string AccessToken { get; set; }

      [JsonProperty(PropertyName = "error")]
      public string Error { get; set; }

      [JsonProperty(PropertyName = "error_description")]
      public string ErrorDescription { get; set; }

    }

  }
}

9
如果你正在使用RestSharp,你需要像这样发起请求:
public static U PostLogin<U>(string url, Authentication obj)
            where U : new()
{
            RestClient client = new RestClient();
            client.BaseUrl = new Uri(host + url);
            var request = new RestRequest(Method.POST);
            string encodedBody = string.Format("grant_type=password&username={0}&password={1}",
                obj.username,obj.password);
            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<U>(request);
            
            return response.Data;
}

1
这很有帮助,谢谢!对于那些想要获取令牌以备后用的人,我只是复制了这个答案,并在 client.Execute 调用之前添加了这一行:request.Resource = "Token"; - Chris

1

我遇到了同样的问题,但只有在令牌URL上使用安全的HTTP才解决了我的问题。参见示例httpclient代码。普通的HTTP在服务器维护后就停止工作了。

var apiUrl = "https://appdomain.com/token"
var client = new HttpClient();    
client.Timeout = new TimeSpan(1, 0, 0);
            var loginData = new Dictionary<string, string>
                {
                    {"UserName", model.UserName},
                    {"Password", model.Password},
                    {"grant_type", "password"}
                };
            var content = new FormUrlEncodedContent(loginData);
            var response = client.PostAsync(apiUrl, content).Result;

是服务器停止接受 HTTP 请求了吗? - OverMars

0
jQuery.ajax({

    "method": "post",
    "url": "https://localhost:44324/token",
    **"contentType": "application/x-www-form-urlencoded",**
    "data": {
      "Grant_type": "password",
      "Username": $('#txtEmail').val(),
      "Password": $('#txtPassword').val()
    }
  })
    .done(function (data) { console.log(data); })
    .fail(function (data) { console.log(data); })

//In Global.asax.cs (MVC WebApi 2)

protected void Application_BeginRequest()

    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        
    }

enter image description here


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

0
在我的情况下,我忘记安装Token.JWT包,所以你也需要在你的项目中安装它。 运行以下命令来安装:Install-Package System.IdentityModel.Tokens.Jwt -Version 6.7.1

0

这可能是协议的原因,需要使用 https://

例如:https://localhost:port/oauth/token


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接