2016-02-28 3 views
0

когда я отправить запрос сообщение для https://accounts.google.com/o/oauth2/token получить ошибку 400Youtube API OAuth 2.0 на UWP ошибки 400

Это мой код

private async Task<string> PostAsync(string requestUriString, List<KeyValuePair<string, string>> content) 
{ 
    string contentString = ""; 
    content.ForEach(kvp => contentString += WebUtility.UrlEncode(kvp.Key) + "=" + WebUtility.UrlEncode(kvp.Value) + "&"); 
    contentString = contentString.Remove(contentString.Length - 1); 

    WebRequest webRequest = WebRequest.Create(requestUriString) as HttpWebRequest; 
    webRequest.Method = "POST"; 
    webRequest.ContentType = "application/x-www-form-urlencoded"; 

    TaskFactory taskFactory = new TaskFactory(); 
    Task<Stream> requestTask = taskFactory.FromAsync(webRequest.BeginGetRequestStream, webRequest.EndGetRequestStream, null); 
    using (Stream requestStream = await requestTask) 
    { 
     using (StreamWriter streamWriter = new StreamWriter(requestStream)) 
     { 
      streamWriter.Write(contentString); 
      streamWriter.Dispose(); 
     } 
     requestStream.Dispose(); 
    } 

    string responseString = null; 
    Task<WebResponse> responseTask = taskFactory.FromAsync(webRequest.BeginGetResponse, webRequest.EndGetResponse, null); 
    WebResponse webResponse = await responseTask; 
    using (Stream responseStream = webResponse.GetResponseStream()) 
    { 
     using (StreamReader streamReader = new StreamReader(responseStream)) 
     { 
      responseString = streamReader.ReadToEnd(); 
      streamReader.Dispose(); 
     } 
     responseStream.Dispose(); 
    } 
    return responseString; 
} 

private async void WebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args) 
{ 
    if (webView.DocumentTitle.StartsWith("Success code=")) 
    { 
     string autorizationCode = webView.DocumentTitle.Substring(13); 
     string responseString = await PostAsync("https://accounts.google.com/o/oauth2/token?", 
      new List<KeyValuePair<string, string>> 
      { 
        new KeyValuePair<string, string>("code",autorizationCode), 
        new KeyValuePair<string, string>("client_id","xxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"), 
        new KeyValuePair<string, string>("client_secret","xxxxxxxxxxxxxx"), 
        new KeyValuePair<string, string>("redirect_uri","http://localhost/oauth2callback"), 
        new KeyValuePair<string, string>("grant_type","authorization_code") 
      } 
     ); 
     MessageDialog dialog = new MessageDialog(responseString); 
     await dialog.ShowAsync(); 
    } 
} 

ответ

2

Если вы используете API данных YouTube в UWP приложение, то поток OAuth 2.0 будет похож на installed application flow, который поддерживает приложения, установленные на устройстве, такие как телефон или компьютер.

Чтобы получить токен доступа, мы можем выполнить шаги в Obtaining OAuth 2.0 access tokens. В UWP мы можем использовать класс WebAuthenticationBroker для запуска операции аутентификации.

Брокер веб-аутентификации позволяет приложениям использовать интернет-аутентификацию и протоколы авторизации, такие как OpenID или OAuth, для подключения к онлайн-провайдерам идентификации. Приложение может использовать брокер веб-аутентификации для входа в веб-службы на основе протокола OAuth или OpenID, такие как многие сайты социальной сети и обмена фотографиями, при условии, что конкретный поставщик услуг внесла необходимые изменения.

Для получения дополнительной информации см. Web authentication broker.

Ниже приведен пример о том, как получить маркер доступа с WebAuthenticationBroker класса и Windows.Web.Http.HttpClient класса:

String YouTubeURL = "https://accounts.google.com/o/oauth2/auth?client_id=" + Uri.EscapeDataString(ClientID) + "&redirect_uri=" + Uri.EscapeDataString("urn:ietf:wg:oauth:2.0:oob") + "&response_type=code&scope=" + Uri.EscapeDataString("https://www.googleapis.com/auth/youtube"); 

Uri StartUri = new Uri(YouTubeURL); 
// As I use "urn:ietf:wg:oauth:2.0:oob" as the redirect_uri, the success code is displayed in the html title of following end uri 
Uri EndUri = new Uri("https://accounts.google.com/o/oauth2/approval?"); 

WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, StartUri, EndUri); 
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) 
{ 
    var autorizationCode = WebAuthenticationResult.ResponseData.Substring(13); 
    var pairs = new Dictionary<string, string>(); 
    pairs.Add("code", autorizationCode); 
    pairs.Add("client_id", ClientID); 
    pairs.Add("client_secret", ClientSecret); 
    pairs.Add("redirect_uri", "urn:ietf:wg:oauth:2.0:oob"); 
    pairs.Add("grant_type", "authorization_code"); 

    var formContent = new HttpFormUrlEncodedContent(pairs); 

    var client = new HttpClient(); 
    var httpResponseMessage = await client.PostAsync(new Uri("https://accounts.google.com/o/oauth2/token"), formContent); 
    string response = await httpResponseMessage.Content.ReadAsStringAsync(); 
} 

И response подобен:

enter image description here

Смежные вопросы