Как исправить ошибку «Неверный запрос» при отправке запроса на отдых в единый вход Google Oauth2 в HttpClient - PullRequest
1 голос
/ 28 марта 2019

Я пытаюсь узнать, как реализовать функцию входа в систему Googles Oauth2 SSO. До сих пор я дошел до того, что все работает, за исключением случаев, когда я пытаюсь отправить запрос на "https://accounts.google.com/o/oauth2/token", используя REST в C #, чтобы получить Access_code / Token. Я зарегистрировал свой локальный хост и соответствующий порт на Google и мне удалось заставить мой запрос POST работать в POSTMAN, однако, когда я пытаюсь отправить запрос в C #, мое HttpRequestMessage возвращает 400 неверных запросов.

Сначала у меня есть страница Authorization.aspx, которая запускает команду, которая перенаправляет пользователей на страницу авторизации googles, где пользователь входит в систему, а затем перенаправляется на мою страницу http://localhost:64716/GoogleCallBack.aspx, которая принимает ответ. На странице он берет код авторизации и пытается отправить запрос POST на базовый URL. Я попытался запустить его в POSTMAN, где он работает (хотя только с новым кодом авторизации). Так что я знаю, что это мой код C #, который является проблемой. Я пытался использовать веб-запрос, а также пытался изменить тип носителя на application / Json и application / x-www-form-urlencoded

    protected void Page_Load(object sender, EventArgs e)
    {

        string Error = Request.QueryString["error"];

        string Code = Request.QueryString["code"];
        if (Error != null) { }
        else if (Code != null)
        {

            string UserId = Request.QueryString["state"];
            int Id = Convert.ToInt32(UserId);
            string AccessToken = string.Empty;
            string RefreshToken = ExchangeAuthorizationCode(Id, Code, out AccessToken);
            string Url = "Authorize.aspx?UserId=" + UserId;
            Response.Redirect(Url, true);
        }
    }
    private string ExchangeAuthorizationCode(int userId, string code, out string accessToken)
    {
        string baseurl = "https://accounts.google.com/o/oauth2/token";
        accessToken = string.Empty;
        string ClientSecret = ConfigurationManager.AppSettings["ClientSecrete"];
        string ClientId = ConfigurationManager.AppSettings["ClientId"];

        string RedirectUrl = "http://localhost:64716/GoogleCallBack.aspx";

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseurl);
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/Json"));

            var nvc = new List<KeyValuePair<string, string>>();
            nvc.Add(new KeyValuePair<string, string>("Code", code));
            nvc.Add(new KeyValuePair<string, string>("Client_id", ClientId));
            nvc.Add(new KeyValuePair<string, string>("Client_secret", ClientSecret));
            nvc.Add(new KeyValuePair<string, string>("Redirect_uri", RedirectUrl));
            nvc.Add(new KeyValuePair<string, string>("Grant_type", "authorization_code"));
            nvc.Add(new KeyValuePair<string, string>("access_type", "offline"));

            var req = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress) { Content = new FormUrlEncodedContent(nvc) };
            var resres = client.SendAsync(req).Result;

            return "temp";

        }

    }

Я хочу, чтобы моим ответом был статускод 200 с маркером доступа от Google (как в Почтальоне)

1 Ответ

0 голосов
/ 29 марта 2019

[решено] Это то, что я сделал (с помощью нескольких друзей)

  1. Изменены заголовки на JSON

  2. ПеремещеноБазовый URI для PostAsync ()

  3. Как только я изменил все, что я мог видеть, ошибка была в redirect_Uri, а затем я изменил ее, чтобы она соответствовала той, что в почтальоне.И теперь это работает

    protected void Page_Load(object sender, EventArgs e)
        {
            //you will get this, when any error will occur while authorization otherwise null    
            string Error = Request.QueryString["error"];
            //authorization code after successful authorization    
            string Code = Request.QueryString["code"];
            if (Error != null) { }
            else if (Code != null)
            {
                //Remember, we have set userid in State    
                string UserId = Request.QueryString["state"];
                //Get AccessToken    
                int Id = Convert.ToInt32(UserId);
                string AccessToken = string.Empty;
                string RefreshToken = ExchangeAuthorizationCode(Id, Code, out AccessToken);
                //saving refresh token in database    
                SaveRefreshToken(Id, RefreshToken);
                //Get Email Id of the authorized user    
                string EmailId = FetchEmailId(AccessToken);
                //Saving Email Id    
                SaveEmailId(UserId, EmailId);
                //Redirect the user to Authorize.aspx with user id    
                string Url = "Authorize.aspx?UserId=" + UserId;
                Response.Redirect(Url, true);
            }
        }
    
        private string ExchangeAuthorizationCode(int userId, string code, out string accessToken)
        {
            string baseurl = "https://accounts.google.com/o/oauth2/token";
            accessToken = string.Empty;
            string ClientSecret = ConfigurationManager.AppSettings["ClientSecrete"];
            string ClientId = ConfigurationManager.AppSettings["ClientId"];
            // //get this value by opening your web app in browser.    
            string RedirectUrl = "http://localhost:64716/GoogleCallback.aspx"; //I changed this to match the one in Postman
    
            using (var client = new HttpClient())
            {
                //client.BaseAddress = new Uri("https://accounts.google.com/o/oauth2"); //I replaced the Uri to "var result = client.PostAsync("https://accounts.google.com/o/oauth2/token", nvc).Result;"
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // I made this JSON
                // I removed this "client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");"
    
                var nvc = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string, string>("grant_type", "authorization_code"),
                new KeyValuePair<string, string>("code", code),
                new KeyValuePair<string, string>("client_id", ClientId),
                new KeyValuePair<string, string>("client_secret", ClientSecret),
                new KeyValuePair<string, string>("redirect_uri", RedirectUrl),
                new KeyValuePair<string, string>("access_type", "offline")
                });
    
                var result = client.PostAsync("https://accounts.google.com/o/oauth2/token", nvc).Result;
    
                var resultContent = result.Content.ReadAsStringAsync();
    
                var tokenResponse = JsonConvert.DeserializeObject<Authorization_request_body>(resultContent.ToString());
    
                return "temp";
    
                }
    
            }
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...