简体   繁体   English

谷歌日历 Web API .NET CORE

[英]GoogleCalendar Web API .NET CORE

Earlier, I have synced googlecalendar with GoogleWebAuthorizationBroker function, it worked great in localhost but not after deploying in server, so I changed the code with GoogleAuthorizationCodeFlow.早些时候,我已将 googlecalendar 与 GoogleWebAuthorizationBroker function 同步,它在 localhost 中运行良好,但在服务器中部署后效果不佳,因此我使用 GoogleAuthorizationCodeFlow 更改了代码。 Here is my code but I don't know where I am wrong.这是我的代码,但我不知道我错在哪里。 Can someone help me?有人能帮我吗? New code but again not working in server新代码但再次无法在服务器中运行

          public async Task<IActionResult> GetGoogleCalendar()
        {
            try
            {
                string[] scopes = { CalendarService.Scope.Calendar }; ;
                var secrets = new ClientSecrets()
                {
                    ClientSecret = "xx",
                    ClientId = "xx.apps.googleusercontent.com"
              
            };
                var credential = await GetGoogleCalendar1(User.Identity.Name, scopes, secrets);
                var service = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Calendar App"
                });
                // Define parameters of request.
                EventsResource.ListRequest request = service.Events.List("primary");
                request.ShowDeleted = false;
                request.SingleEvents = true;
                request.MaxResults = 10;
                request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
                // List events.
                Events events = request.Execute();
                return Json(events.Items);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }

        private async Task<UserCredential> GetGoogleCalendar1(string key, string[] scopes, ClientSecrets gsec)
        {
            try
            {
                var initializer = new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = gsec,
                    Scopes = scopes
                };
                initializer.DataStore = new FileDataStore("OAuth", true);
                var flow = new GoogleAuthorizationCodeFlow(initializer);

                var token = await initializer.DataStore.GetAsync<TokenResponse>(key);
                if (token == null)
                {
                    var result = await AuthorizeAsync(initializer, key);
                    return new UserCredential(result.Flow, key, result.Token);
                }
                return new UserCredential(flow, key, token);
            }
            catch (Exception ex)
            {
                System.IO.File.WriteAllText("error.txt", ex.Message);
                return null;
            }
        }

        private async Task<UserCredential> AuthorizeAsync(GoogleAuthorizationCodeFlow.Initializer initializer, string user)
        {
            var flow = new GoogleAuthorizationCodeFlow(initializer);
            var codeReceiver = new LocalServerCodeReceiver();

            // Create an authorization code installed app instance and authorize the user.
            return await new AuthorizationCodeInstalledApp(flow, codeReceiver).AuthorizeAsync
                (user, CancellationToken.None).ConfigureAwait(false);
        }

credential.json 

{"web":{"client_id":"xx.apps.googleusercontent.com","project_id":"quickstart-1582532911787","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":"xx","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","domain"]}}



startup.cs

    .AddGoogle("GoogleCalendar", "GoogleCalendar", googleOptions =>
                {
                    googleOptions.CallbackPath = new PathString("/signin-google-calendar");
                    googleOptions.ClientId = "xx.apps.googleusercontent.com";
                    googleOptions.ClientSecret = "xx";
                    googleOptions.AccessType = "offline";
                    googleOptions.SaveTokens = true;
                    googleOptions.Scope.Add(Google.Apis.Calendar.v3.CalendarService.Scope.Calendar);
                })

GoogleWebAuthorizationBroker.AuthorizeAsync is designed for use with installed applications. GoogleWebAuthorizationBroker.AuthorizeAsync 设计用于已安装的应用程序。 It will open the login and consent screen on the machine that it is running on.它将在运行它的机器上打开登录和同意屏幕。 This will work fine on your machine in development but in the case of something hosted via IIS this will not work as its going to try and open the browser window on the server and not on the users machine.这将在您正在开发的机器上正常工作,但对于通过 IIS 托管的东西,这将不起作用,因为它将尝试在服务器上而不是在用户机器上打开浏览器 window。

for asp .net core you need to be adding the following to dependency injection对于 asp .net 核心,您需要将以下内容添加到依赖注入

 .AddGoogleOpenIdConnect(options =>
        {
            IConfigurationSection googleAuthSection = Configuration.GetSection("Authentication:Google");
            options.ClientId = googleAuthSection["ClientId"];
            options.ClientSecret = googleAuthSection["ClientSecret"];
            options.Scope.Add(Google.Apis.Calendar.v3.CalendarService.Scope.Calendar);
        });

I have a related question here Connect to Google api via asp .net core causes endless authorization loop我在这里有一个相关的问题Connect to Google api via asp .net core 导致无限的授权循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM