502 Недействительный ответ при вызове Google Api с сайта Azure - программирование

502 Недействительный ответ при вызове Google Api с сайта Azure

Когда я вызываю API Google с веб-сайта Azure, я получаю 502 - веб-сервер получил недопустимый ответ, выступая в качестве шлюза или прокси-сервера. Точный код работает как с моей локальной машины, так и с Azure VM.

Код - это просто получить отображаемое имя из идентификатора пользователя Google

private string GetUserDetails(string userId)
{
    var serviceAccountEmail = "[email protected]nt.com";
    var certFile = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/googlekey.p12");
    var certificate = new X509Certificate2(certFile, "notasecret", X509KeyStorageFlags.Exportable);

    var credential = new ServiceAccountCredential(
       new ServiceAccountCredential.Initializer(serviceAccountEmail)
       {
           Scopes = new[] { PlusService.Scope.PlusMe }
       }.FromCertificate(certificate));

    var service = new PlusService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "Bayfront"
    });

    var request = service.People.Get(userId);
    var person = request.Execute();
    return person.DisplayName;
}

Это вызывалось в проекте WebApi, но я извлек его в одну веб-форму asp.net на странице http://testgplus.azurewebsites.net/

Я также попробовал простой клиент REST с ApiKey вместо использования вышеперечисленного. Опять же, это работает на виртуальной машине, но не на веб-сайте, где я получаю 403 Forbidden. Я добавил IP-адреса веб-сайта и виртуальной машины в Google Developers Console.

private string GetUserDetails2(string userId)
{
    var client = new RestClient("https://www.googleapis.com/plus/v1/people/" + userId);
    var request = new RestRequest(Method.GET);
    request.AddParameter("key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    var response = client.Execute(request);
    if (response.StatusCode == HttpStatusCode.OK)
    {
        dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Content);

        return result["name"]["givenName"];
    }
    return response.StatusCode.ToString();
}

Похоже, я не могу вызывать внешнюю веб-службу для веб-сайта Azure. Я видел некоторые подобные проблемы, например. 502, запрашивающий оплату услуг на веб-сайте azure, но ни одно из предложений не сработало. Кто-нибудь получил какие-либо идеи о том, что может быть причиной или исправить?

4b9b3361

Ответ 1

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

var certificate = new X509Certificate2(p12Path, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
//(notice the X509KeyStorageFlags.MachineKeySet |)

Ответ 2

. Привет, Колин Мировский

Где вы создаете сертификат, метод Application_Start или WebApiConfig Register?

где используется этот код?

makecert -r -n "CN=abdullahsargin.com, [email protected]" -sky exchange -b 11/01/2015 -pe -sv myhost.pvk myhost.cer

pvk2pfx -pvk myhost.pvk -spc myhost.cer -pfx myhost.pfx -po Test.123

В global.asax application_start

         try
        {
            var certFile = Server.MapPath("~/App_Data/myhost.pfx");
            var cert = new X509Certificate2(certFile, "Test.123",
                X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
        }
        catch (Exception exc)
        {
            _tools.LogError(exc);
        }

. этот метод работает на локальном, но в лазурном порядке получает 502 на этом коде, я проверяю эту строку и строку метода

  var code = await _userManager.GeneratePasswordResetTokenAsync(user.Id);

завершает этот метод

    [HttpGet, AllowAnonymous]
    public async Task<HttpResponseMessage> ForgotPassword([FromUri] ForgotPasswordViewModel model)
    {
        try
        {               
            var code = await _userManager.GeneratePasswordResetTokenAsync(user.Id);

            return Request.CreateResponse(HttpStatusCode.OK, new { model = user });

            var url = "http://abdullahsargin.com#/account/resetPassword/" + user.Id + "/" + code;

            await _userManager.SendEmailAsync(user.Id, "Reset Password",
            "Please reset your password by clicking here: <a href=\"" + url + "\">link</a>");

            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (Exception exc)
        {
            MyTools.LogError(exc.GetBaseException());
            return Request.CreateResponse(HttpStatusCode.BadRequest, exc.GetBaseException());
        }
    }

Я нахожу на этой странице свое решение

Идентификация ASP.NET: используйте GeneratePasswordResetToken на веб-сайте Azure

для моего решения

public UserManager() : base(new UserStore<ApplicationUser>(new MyDbContext()))
{
    // other setup
    this.UserTokenProvider = new TotpSecurityStampBasedTokenProvider<ApplicationUser, string>();
}