使用GoogleWebAuthorizationBroker.AuthorizeAsync时发生HttpListenerException "访问被拒绝"。

4
我将为您翻译以下关于 IT 技术的内容,它涉及 OAuth2 以及 Azure 托管的 Web 应用程序。在这里有许多解决方案可供使用,但它们都采用了服务帐户/证书,而我需要用户通过 Google 进行身份验证和授权。

代码:

var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
    new ClientSecrets { ClientId = _clientId, ClientSecret = _clientSecret },
    scopes,
    User.Identity.Name,
    CancellationToken.None,
    new FileDataStore("GA.Auth.Store")) /* tried this to be null as well */
    .Result;

var service = new AnalyticsService(
    new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "Analytics API Sample"
    });

在本地运行正常,但在部署为Azure Web应用程序时出现以下异常:
[HttpListenerException (0x5): Access is denied]
Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +82
Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task) +76
Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__1.MoveNext() +233

我猜 GoogleWebAuthorizationBroker.AuthorizeAsync 正试图建立一个 http 监听器,而这在 Azure web 应用程序中不可能(?)。
我尝试使用 Azure web 应用程序身份验证。这确实对用户进行了身份验证,但是我该如何检索经过身份验证的用户以便将其授权给 Google?
顺便说一下:因为我需要 GA 实时数据,所以我被困在 GA Reporting v3 库中。

我想了解如何在Azure网站上设置谷歌授权?您可以参考这份文档(https://azure.microsoft.com/zh-cn/documentation/articles/app-service-mobile-how-to-configure-google-authentication/)。 - Will Shao - MSFT
是的,使用 Azure 的新界面,导航到应用程序设置并选择身份验证/授权... - Dmitry
我猜程序在本地运行是因为你使用管理员权限运行它,而这种权限在Azure托管中不可用... 无论如何,你能找到解决这个问题的方法吗? - AntonK
1个回答

0

GoogleWebAuthorizationBroker.AuthorizeAsync是为安装的应用程序设计的,它不适用于托管,因为它将尝试在服务器上打开Web浏览器窗口以获得同意。

您应该遵循web示例。

public void ConfigureServices(IServiceCollection services)
{
    ...

    // This configures Google.Apis.Auth.AspNetCore3 for use in this app.
    services
        .AddAuthentication(o =>
        {
            // This forces challenge results to be handled by Google OpenID Handler, so there's no
            // need to add an AccountController that emits challenges for Login.
            o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
            // This forces forbid results to be handled by Google OpenID Handler, which checks if
            // extra scopes are required and does automatic incremental auth.
            o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
            // Default scheme that will handle everything else.
            // Once a user is authenticated, the OAuth2 token info is stored in cookies.
            o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddGoogleOpenIdConnect(options =>
        {
            options.ClientId = {YOUR_CLIENT_ID};
            options.ClientSecret = {YOUR_CLIENT_SECRET};
        });
}
      

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接