要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