Besar Bajrami
Besar Bajrami

Reputation: 1

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. 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);
                })

Upvotes: 0

Views: 914

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116948

GoogleWebAuthorizationBroker.AuthorizeAsync is designed for use with installed applications. 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.

for asp .net core you need to be adding the following to dependency injection

 .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

Upvotes: 2

Related Questions