Как сгенерировать токен обновления и доступа для приложения Windows phone

У меня есть приложение для Windows Phone 8, и я пытаюсь выполнить Google Auth. Я попадаю на страницу входа, и после входа я попадаю на страницу согласия. После нажатия кнопки «Разрешить доступ» я не получаю токен доступа и не обновляю токен в ответ.

Я получаю следующий ответ:

{
"error" : "invalid_request",
"error_description" : "Missing header: Content-Type"
}

StatusCode - Плохой запрос.

Вот мой код:

private void webBrowserGooglePlusLogin_Navigating(object sender, NavigatingEventArgs e)
    {

        if (e.Uri.Host.Equals("localhost"))
        {
            webBrowserGooglePlusLogin.Visibility = Visibility.Collapsed;
            e.Cancel = true;
            int pos = e.Uri.Query.IndexOf(" = ");              
            code = pos > -1 ? e.Uri.Query.Substring(pos + 1) : null;
        }
        if (string.IsNullOrEmpty(code))
        {
           // OnAuthenticationFailed();
        }
        else
        {
            var request = new RestRequest(this.TokenEndPoint, Method.POST);
            request.AddParameter("code", code);
            request.AddParameter("client_id", this.ClientId);
            request.AddParameter("client_secret", this.Secret);
            request.AddParameter("redirect_uri", "http://localhost");
            request.AddParameter("grant_type", "authorization_code");
            //request.AddHeader("Content-type", "json");

            client.ExecuteAsync<AuthResult>(request, GetAccessToken);
        }
    }

    void GetAccessToken(IRestResponse<AuthResult> response)
    {
        if (response == null || response.StatusCode != HttpStatusCode.OK
            || response.Data == null || string.IsNullOrEmpty(response.Data.access_token))
        {
           // OnAuthenticationFailed();
        }
        else
        {               
        }
    }

Любая помощь приветствуется.

Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
0
63
1

Ответы 1

Необходимо указать тип контента

request.ContentType = "application/x-www-form-urlencoded";

Это мой образец .net, я не уверен, что все работает на Windows Phone, но это может помочь.

 class TokenResponse
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string refresh_token { get; set; }
    }

/// <summary>

        /// exchanges the authetncation code for the refreshtoken and access token
        /// </summary>
        /// <param name = "code"></param>
        /// <returns></returns>
        public static string exchangeCode(string code)
        {


            string url = "https://accounts.google.com/o/oauth2/token";
            string postData = string.Format("code = {0}&client_id = {1}&client_secret = {2}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code", code, Properties.Resources.clientId, Properties.Resources.secret);


            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create(url);
            // Set the Method property of the request to POST.

            request.Method = "POST";

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            TokenResponse tmp = JsonConvert.DeserializeObject<TokenResponse>(responseFromServer);

            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
            return tmp.refresh_token;
        }

Oauth простой

Другие вопросы по теме