我正在尝试用授权码交换访问令牌。我正在使用ASP.NET中的HttpClient
进行后期请求:
var clientId = "clientid";
var redirectUri = "http://localhost:65148/Welcome";
var clientSecret = "clientsecret";
if (code != null)
{
//Lets exchange the code for a access token
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "code", code },
{ "client_id", clientId },
{ "client_secret", clientSecret },
{ "redirect_uri", redirectUri },
{ "grant_type", code }
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://accounts.google.com/o/oauth2/token", content);
var responseString = await response.Content.ReadAsStringAsync();
var value = Json(new { data = responseString });
return value;
}
}
但当我运行此程序时,我会收到一条错误消息:
{
"error" : "invalid_request",
"error_description" : "Invalid grant_type:4/AlxtyFqHeOiTC32THJgipkUWtHBO27GqFfgOoOCG9wE"
}
我不知道我为什么会得到这个。
在您提供的链接中,声明grant_type
应设置为authorization_code。我可以看出这是令人困惑的(也许它应该是代码的值?),但在本示例的后面,它被澄清为"authorization_code"的字符串文字。
A sample request is displayed below:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf&
client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com&
client_secret=hDBmMRhz7eJRsM9Z2q1oFBSe&
redirect_uri=http://localhost/oauth2callback&
**grant_type=authorization_code**
也许更有趣的是,grant_type
是OAuth 2.0的标准,根据场景的不同,它被限制为某些值。您的场景,授权代码授予,在规范的这一部分中进行了描述:https://www.rfc-editor.org/rfc/rfc6749#section-4.1
来自文档:
grant_type必需。值必须设置为"0";authorization_code";。