GoogleWebAuthorizationBroker 问题,但在 .NET Framework 4.8 应用程序中

问题描述 投票:0回答:1

我在使用 Google Gmail API 时遇到问题。它在我的本地计算机上运行,但是一旦我将项目部署到服务器,它就停止运行。

错误:

System.AggregateException: One or more errors occurred. ---> System.NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&code_challenge=tDq__xCgypmYKgfwjD0nAcV7mMU6rWMS2Hm_UqPqbTY&code_challenge_method=S256&response_type=code&client_id=180884391537-6lvtccf5rot6a124v9qb4coilhmtv3fe.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A64176%2Fauthorize%2F&scope=https%3A%2F%2Fmail.google.com%2F%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.modify%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.send%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email" for authorization. See inner exception for details. ---> System.ComponentModel.Win32Exception: Access is denied
   at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
   at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.OpenBrowser(String url)
   at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.<ReceiveCodeAsync>d__13.MoveNext()
   --- End of inner exception stack trace ---
   at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.<ReceiveCodeAsync>d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.<AuthorizeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__1.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()

我有一个 .NET Framework 4.8 中的应用程序,我想从用户在我的应用程序中关联的帐户访问 Gmail 电子邮件。在 Google 开发者控制台中,我为 Web 应用程序和桌面应用程序创建了 OAuth 2.0 凭据。在本地级别,它工作得很好,因为我们使用 GoogleWebAuthorizationBroker,但在生产中会出现错误,当它是一个 Web 应用程序时,此方法不允许我验证或授权 Google 帐户返回令牌。我询问了 Google.Apis.Auth.AspNetCore3,但我的理解是它适用于 .NET Core 3 应用程序,而不是 .NET Framework。我不知道它是什么或从哪里开始。代码如下:

        private static readonly string credentialsPathDesktop = HttpContext.Current.Server.MapPath("~/App_Data/IntegracionesCRM/Credentials/Google/client_secrets.json");
        private static readonly string credentialsPathWebApp = HttpContext.Current.Server.MapPath("~/App_Data/IntegracionesCRM/Credentials/Google/client_secret_webApp.json");
        private static readonly string[] Scopes = { Scope.MailGoogleCom, Scope.GmailModify, Scope.GmailSend, "https://www.googleapis.com/auth/userinfo.email" };

        // Authorizing a service account with workspace
        public LoadServiceGoogle LoadGoogleCredentials(int gdtnegociotipo)
        {
            context.Configuration.LazyLoadingEnabled = false;
            var tipo = context.gdtnegociotipoes.SingleOrDefault(x => x.gdtnegociotipoid == gdtnegociotipo);

            using (var stream = new FileStream(credentialsPathDesktop, FileMode.Open, FileAccess.Read))
            {
                var clientSecrets = GoogleClientSecrets.FromStream(stream).Secrets; // Accede a la propiedad Secrets del objeto GoogleClientSecrets

                try
                {
                    // Genering a random user id to avoid conflicts
                    string userIdPrefix = "user_";
                    string userId = userIdPrefix + Guid.NewGuid().ToString();
                    string tokensPath = HttpContext.Current.Server.MapPath(string.Format("~/App_Data/IntegracionesCRM/Tokens/TiposID/{0}", tipo.gdtnegociotipoid));

                    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                                           clientSecrets,
                                           Scopes,
                                           userId,
                                           CancellationToken.None,
                                           new FileDataStore(tokensPath)).Result;

                    return new LoadServiceGoogle { credential = credential, tokensFolderPath = tokensPath, credentialsPath = credentialsPathDesktop, userId = userId };
                }
                catch (Exception ex)
                {
                    throw new SecurityAccessDeniedException("Error al obtener las credenciales de Google", ex);
                }
            }
        }
c# google-oauth gmail-api google-api-dotnet-client .net-4.8
1个回答
1
投票

GoogleWebAuthorizationBroker.AuthorizeAsync 设计用于与已安装的应用程序一起使用,并且不适用于网络应用程序,因为它将尝试在运行代码的计算机上打开同意屏幕,在这种情况下,您的网络服务器基本上您正在使用代码错误

不幸的是,我不知道任何旧版本的工作示例代码,所以我无法提供更多帮助

© www.soinside.com 2019 - 2024. All rights reserved.