Twilio / Authy возвращает 401 с кодом подтверждения - PullRequest
0 голосов
/ 22 мая 2018

Это для 2FA при входе в мое приложение.У меня есть два открытых метода асинхронных задач в моем контроллере.Первый работает отлично.Нет ошибок, если только номер телефона пользователя не совпадает с тем, что есть в базе данных.вот этот метод:

[HttpPost]
    public async Task<ActionResult> StartVerifyPhoneAsync(AuthyModel authyModel)
    {
        string mobileNumber = authyModel.MobileNumber.Replace(@"-", "");
        if(mobileNumber != Session["MobileNumber"].ToString())
        {
            Session["AuthyError"] = "Invalid Phone Number";
            return View();
        }
        // Create client
        var client = new HttpClient();

        // Add authentication header
        client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthKey);

        var values = new Dictionary<string, string>
        {
            { "via", "sms" },
            {"phone_number", mobileNumber },
            {"country_code", "1" },
            {"code_length", "6" }
        };

        var content = new FormUrlEncodedContent(values);

        var url = $"https://api.authy.com/protected/json/phones/verification/start?api_key=" + AuthKey;

        HttpResponseMessage response = await client.PostAsync(url, content);
        if (response.IsSuccessStatusCode)
        {
            return View("VerificationCode");
        }
        else
        {
            Session["AuthyErrors"] = response.ReasonPhrase;
            return View("Index");
        }
    }

В моем следующем методе я делаю в точности так, как говорит ответ на этот вопрос Twilio Authy

Однако возвращается и неавторизованный статускод, 401:

[HttpGet]
    public async Task<ActionResult> CheckVerifyPhoneAsync(AuthyModel authyModel)
    {
        if(Session["VerifyAttempt"] == null || Session["VerifyAttempt"].ToString() == "")
        {
            Session["VerifyAttempt"] = "1";
        }

        int verifyAttempt = int.Parse(Session["VerifyAttempt"].ToString());

        if (verifyAttempt < 3)
        {
            string mobileNumber = Session["MobileNumber"].ToString();

            string code = "";
            if(!String.IsNullOrEmpty(authyModel.VerificationCode))
            {
                code = authyModel.VerificationCode.Trim();
            }

            // Create client
            var client = new HttpClient();

            // Add authentication header
            client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthKey);

            var phone_number = mobileNumber;
            var country_code = "1";
            var verification_code = code;
            var url = $"https://api.authy.com/protected/json/phones/verification/start?api_key=" + AuthKey + "&phone_number=" + phone_number + "&country_code=" + country_code + "&verification_code=" + verification_code;

            HttpResponseMessage response = await client.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                //removed for stackoverflow view
            }
            else
            {
                Session["AuthyErrors"] = response.StatusCode;
                Session["VerifyAttempt"] = (int.Parse(Session["VerifyAttempt"].ToString()) + 1).ToString();
                return View("VerificationCode");
            }
        }
        else
        {
            return RedirectToAction("Logout", "Home");
        }

    }

Вот ответ:

{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: 
    System.Net.Http.StreamContent, Headers:
{
      Connection: keep-alive
      Status: 401 Unauthorized
      X-Content-Type-Options: nosniff
      Date: Tue, 22 May 2018 18:22:42 GMT
      Server: //removed for Stackoverflow
      Server: (Ubuntu)
      WWW-Authenticate: Basic realm="Access Denied"
      Content-Length: 247
      Content-Type: application/json; charset=utf-8
}}

Любая помощь будет высоко ценится.Я не могу понять, как обойти эту ошибку 401 или почему я ее получаю.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...