Опитах се да внедря Yahoo OAuth 2.0 със следното ръководство: https://developer.yahoo.com/oauth2/guide/ Успях да упълномощя и получих код за оторизация, но се провалих на стъпка 4. Когато кодът ми се опита да обмени код за оторизация за токен за достъп с помощта на /get_token 401, се появява неупълномощена грешка. { "error": "invalid_grant" }
Според https://developer.yahoo.com/oauth2/guide/errors/index.html invalid_grant означава, че е предоставен невалиден или изтекъл токен. Малко съм объркан защо 401 е хвърлен.
Някой имал ли е подобен проблем?
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;
}
}
}
}