![](/img/trans.png)
[英]Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman
[英]C# unsupported grant type when calling web api
我正在嘗試從 c# WPF 桌面應用程序向我的 WebAPI 執行發布。
無論我做什么,我都會得到
{“錯誤”:“不支持的授權類型”}
這是我嘗試過的(並且我已經嘗試了我能找到的一切):
還開發 web api 目前正在測試中: http://studiodev.biz/
基礎 http 客戶端 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 成功撥打電話。
更新提琴手結果
有人可以幫我成功撥打上述 web api ... 如果我能幫助澄清,請告訴我。 謝謝!!
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 傳遞。 你只需要這個來獲取令牌; 對於 API 的其他方法,您可以使用 JSON。
此類問題也在此處討論。
1) 注意 URL:“localhost:55828/token”(不是“localhost:55828/API/token”)
2) 注意請求數據。 它不是json格式,它只是沒有雙引號的普通數據。 “用戶名=xxx@gmail.com&password=Test123$&grant_type=password”
3) 注意內容類型。 內容類型:'application/x-www-form-urlencoded'(不是內容類型:'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 的屏幕截圖:
這是一個工作示例,我曾經使用 SSL 向在端口 43305 上運行的本地 Web API 應用程序發出此請求。 我也把這個項目放到了 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; }
}
}
}
如果您使用的是 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;
}
有同樣的問題,但僅通過令牌 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;
在我的情況下,我忘記安裝安裝包 Token.JWT,所以你也需要在你的項目中安裝。 安裝包 System.IdentityModel.Tokens.Jwt -Version 6.7.1
這可能是協議的原因,它需要 https://
例如:https://localhost:port/oauth/token
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); })
//在 Global.asax.cs (MVC WebApi 2)
受保護的無效 Application_BeginRequest()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.