简体   繁体   中英

Why i am getting Yahoo OAuth 2.0 error (401) Unauthorized?

I am implementing Yahoo OAuth 2.0 given in the guide - https://developer.yahoo.com/oauth2/guide/ I am successful in getting the Access Code given in step 4 but in step 5 which says 'Exchange refresh token for new access token' my code is failing with error - 'The remote server returned an error: (401) Unauthorized.' My application is placed in http://www.example.com/TutorialCode/YahooOAuth2.0/yahoooauth2.aspx and it gets the Access Token. Now i am requesting the new access token from the refresh token in another page - http://www.example.com/TutorialCode/YahooOAuth2.0/newaccesstoken.aspx

that is the refresh token i copy and paste from previous page to this page and click button to get new access token but it is failing. My code is -

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

Can somebody help me in getting the root cause of the problem? Thanks

You need to URL encode the parameter values in the request. They may contain characters like & or = that would break the form encoding.

Other than that you may want to swap the legacy POST approach for a more recent, easier approach, as described in the answer in HTTP request with post

You can check your parameters with a curl command:

curl -u "${consumerKey}:${consumerSecret}" -d "grant_type=refresh_token&redirect_uri=${returnUrl}&refresh_token=${refreshToken}" https://api.login.yahoo.com/oauth2/get_token

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM