要UWP执行的OAuth 2.0认证操作时,我们通常采取的WebAuthenticationBroker Class优势。
Web身份验证代理允许应用程序使用Internet身份验证和授权协议,如OpenID或OAuth连接到在线身份提供程序。应用程序可以选择使用Web身份验证代理来登录基于OAuth或OpenID协议的Web服务,例如许多社交网络和图片共享网站,前提是特定的服务提供商已经进行了必要的更改。
欲了解更多信息,请参阅Web authentication broker。
以下是使用WebAuthenticationBroker类和Windows.Web.Http.HttpClient类的示例。WebAuthenticationBroker
类是用于“同意页面重定向”和Windows.Web.Http.HttpClient
类是用于“获得访问和刷新令牌”。
string startURL = "https://www.inoreader.com/oauth2/auth?client_id=[CLIENT_ID]&redirect_uri=[REDIRECT_URI]&response_type=code&scope=[OPTIONAL_SCOPES]&state=[CSRF_PROTECTION_STRING]";
//endURL is the REDIRECT_URI set in your application registration settings
string endURL = "[REDIRECT_URI]";
System.Uri startURI = new System.Uri(startURL);
System.Uri endURI = new System.Uri(endURL);
// Get Authorization code
var webAuthenticationResult =
await Windows.Security.Authentication.Web.WebAuthenticationBroker.AuthenticateAsync(
Windows.Security.Authentication.Web.WebAuthenticationOptions.None,
startURI,
endURI);
if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
//webAuthenticationResult.ResponseData would like "https://yourredirecturi.com/?code=[AUTHORIZATION_CODE]&state=[CSRF_PROTECTION_STRING]"
var decoder = new WwwFormUrlDecoder(new Uri(webAuthenticationResult.ResponseData).Query);
//Get the CSRF_PROTECTION_STRING and check if it matches that one that you send during the consent page redirection.
if (decoder.GetFirstValueByName("state") == "[CSRF_PROTECTION_STRING]")
{
//Get the AUTHORIZATION_CODE
var autorizationCode = decoder.GetFirstValueByName("code");
//Send a POST request
var pairs = new Dictionary<string, string>();
pairs.Add("code", autorizationCode);
pairs.Add("redirect_uri", [REDIRECT_URI]);
pairs.Add("client_id", [CLIENT_ID]);
pairs.Add("client_secret", [CLIENT_SECRET]);
pairs.Add("scope", [OPTIONAL_SCOPES]);
pairs.Add("grant_type", "authorization_code");
var formContent = new Windows.Web.Http.HttpFormUrlEncodedContent(pairs);
var client = new Windows.Web.Http.HttpClient();
var httpResponseMessage = await client.PostAsync(new Uri("https://www.inoreader.com/oauth2/token"), formContent);
if (httpResponseMessage.IsSuccessStatusCode)
{
//The Response is a JSON string
string jsonString = await httpResponseMessage.Content.ReadAsStringAsync();
var jsonObject = Windows.Data.Json.JsonObject.Parse(jsonString);
//Obtaining access and refresh tokens
var accessToken = jsonObject["access_token"].GetString();
var refreshToken = jsonObject["refresh_token"].GetString();
}
}
}
在使用HttpFormUrlEncodedContent,它应该能够Content-type
头自动设置为application/x-www-form-urlencoded
。
嗨,对不起,我还没有回来。我一直都在等待Inoreader回复我,并提供一些细节来帮助我们继续。我希望下周有机会。很自信,答案是可以接受的;一旦我可以确认,我一定会在这里标记答案。 – Bredcrumbs