首页 > 解决方案 > Google Calendar API 异常“访问被拒绝。” .NET Core Web App 在本地运行良好,在 Azure 上发布时引发异常

问题描述

我编写了一个同步用户的谷歌日历事件的应用程序。当我在本地运行相同的应用程序时,它可以正常工作,但是在 azure 上发布它时会引发以下异常。

System.Net.HttpListenerException (5):访问被拒绝。

应用程序详细信息:ASP.NET MVC 核心、C#

我在 Google 应用程序控制台上为 Web 应用程序创建了客户端 ID。

堆栈跟踪的某些部分如下:

System.Net.HttpListenerException (5): Access is denied.
at System.Net.HttpListener.SetupV2Config()
at System.Net.HttpListener.Start()
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.StartListener()
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.ReceiveCodeAsync(AuthorizationCodeRequestUrl url, CancellationToken taskCancellationToken)
at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.AuthorizeAsync(String userId, CancellationToken taskCancellationToken)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(Initializer initializer, IEnumerable`1 scopes, String user, CancellationToken taskCancellationToken, IDataStore dataStore, ICodeReceiver codeReceiver)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(ClientSecrets clientSecrets, IEnumerable`1 scopes, String user, CancellationToken taskCancellationToken, IDataStore dataStore, ICodeReceiver codeReceiver)

我正在使用以下代码(导致异常):

private CalendarService GetCalendarService(string username)
    {
        UserCredential credential;
      
        //string fileName = "installed_app_secret.json";
        string fileName = "web_app_secret.json";

        string[] scopes = new string[] { CalendarService.Scope.Calendar, CalendarService.Scope.CalendarReadonly };

        string clientSecretFile = Path.Combine(_webRootPath, "App_Data", fileName);

        using (var stream = new FileStream(clientSecretFile, FileMode.Open, FileAccess.Read))
        {
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                scopes,
                username,
                CancellationToken.None,
                new DbDataStore(this._configuration, _attorneyId)).Result;
        }


        // Create Google Calendar API service.
        return new CalendarService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = _APPLICATION_NAME,
        });
    }

此外,我还为 Web 应用程序(未安装的应用程序)生成了 ClientID。Json 文件如下所示:

{
"web": {
"client_id": "xxxxxx",
"project_id": "calendar-sync-app-290311",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "yyyyy",
"redirect_uris": [ "urn:ietf:wg:oauth:2.0:oob",     "https://<path>/oauth2callback" ]
}
}

对此的任何帮助都将受到高度赞赏。

标签: c#azureasp.net-core-mvcgoogle-calendar-api

解决方案


推荐阅读