Zbigniew Winiarski
Zbigniew Winiarski

Reputation: 41

Yahoo OAuth 2.0 invalid_grant when issuing an access token

I tried to implement Yahoo OAuth 2.0 with following guide: https://developer.yahoo.com/oauth2/guide/ I was able to authorize and I received Authorization Code but I sucked at step 4. When my code tries to exchange Authorization Code for Access Token using /get_token 401 Unauthorized Error is thrown. { "error": "invalid_grant" }

According to https://developer.yahoo.com/oauth2/guide/errors/index.html invalid_grant means that an invalid or expired token was provided. I am little bit confused why the 401 is thrown.

Have somebody experienced similar issue?

public class YahooOAuthClient : OAuth2Client
{
    private const string AuthorizeUrl = "https://api.login.yahoo.com/oauth2/request_auth";
    private const string TokenEndpoint = "https://api.login.yahoo.com/oauth2/get_token";

    private readonly string clientId;
    private readonly string clientSecret;

    public YahooOAuthClient(string clientId, string clientSecret)
        : base("Yahoo")
    {
        this.clientId = clientId;
        this.clientSecret = clientSecret;
    }

    protected override Uri GetServiceLoginUrl(Uri returnUrl)
    {
        var uriBuilder = new UriBuilder(AuthorizeUrl);
        uriBuilder.AppendQueryArgument("client_id", this.clientId);
        uriBuilder.AppendQueryArgument("redirect_uri", returnUrl.ToString());
        uriBuilder.AppendQueryArgument("response_type", "code");
        uriBuilder.AppendQueryArgument("language", "en-us");

        return uriBuilder.Uri;
    }

    protected override IDictionary<string, string> GetUserData(string accessToken)
    {
        return new Dictionary<string, string>
        {
            {"id", accessToken}
        };
    }

    protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
    {
        var postData = HttpUtility.ParseQueryString(string.Empty);
        postData.Add(new NameValueCollection
            {
                { "grant_type", "authorization_code" },
                { "code", authorizationCode },
                { "redirect_uri", returnUrl.GetLeftPart(UriPartial.Path) },
            });

        var webRequest = (HttpWebRequest)WebRequest.Create(TokenEndpoint);

        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";
        String encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(clientId + ":" + clientSecret));
        webRequest.Headers.Add("Authorization", "Basic " + encoded);

        using (var s = webRequest.GetRequestStream())
        using (var sw = new StreamWriter(s))
            sw.Write(postData.ToString());

        using (var webResponse = webRequest.GetResponse())
        {
            var responseStream = webResponse.GetResponseStream();
            if (responseStream == null)
                return null;

            using (var reader = new StreamReader(responseStream))
            {
                var response = reader.ReadToEnd();
                var json = JObject.Parse(response);
                var accessToken = json.Value<string>("access_token");
                return accessToken;
            }
        }
    }
}

Upvotes: 4

Views: 1227

Answers (1)

Cyril Tata
Cyril Tata

Reputation: 199

This answer may be late but I ran into the same problem as you though I was implementing with PHP. This is what I realized was my error:

Intially my return_url is of the form

http://example.com/oauth_handle?route=something/path/like&param1=value&param2=value

I was implemting oauth for facebook, twitter(blah), google linkedin and yahoo. Google oauth api didn't like the route=something/path/like so I url-encoded it to

http://example.com/oauth_handle?route=something%2Fpath%2Flike&param1=value&param2=value

So that is the return_uri that was sent to the /request_auth endpoint as-is.

Then for the /get_token then parameter return_uri was url-encoded again which means I was now doing a double url-encoding for the route=something/path/like part which makes the return_uri different in the two requests.

Correcting this by doing url_encode just once solves my problem. Hope this helps!

Upvotes: 0

Related Questions