我正在实施指南中提供的Yahoo OAuth 2.0 - https://developer.yahoo.com/oauth2/guide/ 我成功获取了步骤4中给出的访问代码,但在步骤5中显示“用于新访问令牌的Exchange刷新令牌”,我的代码失败并显示错误 - “远程服务器返回错误:(401)未经授权。” 我的应用程序放在http://www.example.com/TutorialCode/YahooOAuth2.0/yahoooauth2.aspx中,它获得了访问令牌。 现在我从另一个页面中的刷新令牌请求新的访问令牌 - http://www.example.com/TutorialCode/YahooOAuth2.0/newaccesstoken.aspx
这是我从上一页复制并粘贴到此页面的刷新令牌,然后单击按钮获取新的访问令牌,但它失败了。我的代码是 -
HTML
<asp:TextBox placeholder="Refresh Token" ID="refreshTokenTextBox" runat="server"></asp:TextBox>
<asp:Button ID="newAccessTokenButton" runat="server" Text="Get New Access Token" OnClick="newAccessTokenButton_Click" />
<div id="newDataDiv" runat="server"></div>
C#
protected void newAccessTokenButton_Click(object sender, EventArgs e)
{
string consumerKey = "xxxx";
string consumerSecret = "myconsumerkey";
string returnUrl = "http://www.example.com/TutorialCode/YahooOAuth2.0/newaccesstoken.aspx";
//string encodedReturnUrl = System.Web.HttpUtility.UrlEncode(returnUrl);
/*Exchange authorization code for Access Token by sending Post Request*/
Uri address = new Uri("https://api.login.yahoo.com/oauth2/get_token");
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] headerByte = System.Text.Encoding.UTF8.GetBytes(consumerKey + ":" + consumerSecret);
string headerString = System.Convert.ToBase64String(headerByte);
request.Headers["Authorization"] = "Basic " + headerString;
// Create the data we want to send
StringBuilder data = new StringBuilder();
data.Append("client_id=" + consumerKey);
data.Append("&client_secret=" + consumerSecret);
data.Append("&redirect_uri=" + returnUrl);
data.Append("&refresh_token =" + refreshTokenTextBox.Text.Trim());
data.Append("&grant_type=refresh_token");
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
string responseFromServer = "";
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
responseFromServer = reader.ReadToEnd();
//ShowNewReceivedData(responseFromServer);
newDataDiv.InnerHtml = responseFromServer;
}
}
catch (Exception ex)
{
Response.Write(ex.Message+"<br/>"+ex.ToString());
}
}
有人可以帮我解决问题的根本原因吗? 感谢
答案 0 :(得分:0)
您需要对请求中的参数值进行URL编码。它们可能包含&
或=
等字符,会破坏表单编码。
除此之外,您可能希望将旧版POST方法换成更新,更简单的方法,如HTTP request with post
中的答案所述您可以使用curl命令检查参数:
curl -u "${consumerKey}:${consumerSecret}" -d "grant_type=refresh_token&redirect_uri=${returnUrl}&refresh_token=${refreshToken}" https://api.login.yahoo.com/oauth2/get_token