Beispiel #1
0
        private async Task Run()
        {
            UserCredential credential;
            var            path = Directory.GetCurrentDirectory() + @"\wwwroot\client_secrets.json";

            using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                dsAuthorizationBroker.RedirectUri = "http://*****:*****@gmail.com", CancellationToken.None, new FileDataStore("c://tmep")
                                                                        );

                //credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                //    GoogleClientSecrets.Load(stream).Secrets,
                //    new[] { BooksService.Scope.Books },
                //    "*****@*****.**", CancellationToken.None, new FileDataStore("c://tmep")
                //    );
            }

            // Create the service.
            var service = new BooksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Paluga",
            });

            // Revoke the credential.
            Console.WriteLine("\n!!!REVOKE ACCESS TOKEN!!!\n");
            await credential.RevokeTokenAsync(CancellationToken.None);

            // Reauthorize the user. A browser should be opened, and the user should enter his or her credential again.
            await GoogleWebAuthorizationBroker.ReauthorizeAsync(credential, CancellationToken.None);
        }
        static public void ReInit(long chatId)
        {
            using (var stream =
                       new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";

                if (credential == null)
                {
                    credential = Init(chatId);
                }
                else
                {
                    try
                    {
                        GoogleWebAuthorizationBroker.ReauthorizeAsync(
                            credential,
                            CancellationToken.None);
                        Console.WriteLine("Credential file saved to: " + credPath);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        return;
                    }
                }
            }
        }
        public static async Task <ContactsRequest> LoginToContactsService(string user, IWebProxy proxyOrNull)
        {
            var clientSecrets = CreateClientSecrets();
            var credential    = await LoginToGoogle(user, proxyOrNull);

            var parameters      = CreateOAuth2Parameters(clientSecrets, credential);
            var contactsRequest = new ContactsRequest(CreateRequestSettings(parameters));

            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));

            query.NumberToRetrieve = 1;
            try
            {
                var feed = contactsRequest.Service.Query(query);
            }
            catch (GDataRequestException x)
            {
                s_logger.Error("Trying to access google contacts API failed. Revoking  token and reauthorizing.", x);

                await credential.RevokeTokenAsync(CancellationToken.None);

                await GoogleWebAuthorizationBroker.ReauthorizeAsync(credential, CancellationToken.None);

                parameters      = CreateOAuth2Parameters(clientSecrets, credential);
                contactsRequest = new ContactsRequest(CreateRequestSettings(parameters));
            }

            if (proxyOrNull != null)
            {
                contactsRequest.Proxy = proxyOrNull;
            }

            return(contactsRequest);
        }
Beispiel #4
0
        public async Task <BooksService> Authenticate()
        {
            UserCredential credential;

            using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { BooksService.Scope.Books },
                    "user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
            }

            if (credential.Token == null || credential.Token.IsExpired(SystemClock.Default))
            {
                await GoogleWebAuthorizationBroker.ReauthorizeAsync(credential, CancellationToken.None);
            }

            //await credential.RevokeTokenAsync(CancellationToken.None);

            var service = new BooksService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Books API",
            });

            return(service);
        }
Beispiel #5
0
 public long?GMailCheckMessages()
 {
     // Request should fail now - invalid grant.
     try
     {
         return(TryGMailCheckMessages());
     }
     catch (TokenResponseException)
     {
         GoogleWebAuthorizationBroker.ReauthorizeAsync(_credential, CancellationToken.None);
         return(TryGMailCheckMessages());
     }
 }
 private void btRelogin_Click(object sender, EventArgs e)
 {
     if (credential != null)
     {
         if (CheckForInternetConnection())
         {
             var task = GoogleWebAuthorizationBroker.ReauthorizeAsync(credential, CancellationToken.None);
         }
         else
         {
             MessageBox.Show("No internet connection available");
         }
     }
     else
     {
         MessageBox.Show("You are not logged, press button 'Log In / Load event'");
     }
 }
Beispiel #7
0
        public void Authenticate(string clientSecrets, bool reauthenticate)
        {
            string[] scopes = { "https://www.googleapis.com/auth/photoslibrary.readonly" };

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(clientSecrets)))
            {
                UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    scopes,
                    GoogleUserName,
                    CancellationToken.None,
                    new FileDataStore("GooglePhotosDownloader", false)).Result;

                if (reauthenticate)
                {
                    GoogleWebAuthorizationBroker.ReauthorizeAsync(UserCredential, CancellationToken.None).Wait();
                }
            }
        }
Beispiel #8
0
        private async Task Run()
        {
            UserCredential credential;

            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { BooksService.Scope.Books },
                    "user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
            }

            // Create the service.
            var service = new BooksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Books API Sample",
            });

            // List library.
            await ListLibrary(service);

            // Revoke the credential.
            Console.WriteLine("\n!!!REVOKE ACCESS TOKEN!!!\n");
            await credential.RevokeTokenAsync(CancellationToken.None);

            // Request should fail now - invalid grant.
            try
            {
                await ListLibrary(service);
            }
            catch (TokenResponseException ex)
            {
                Console.WriteLine(ex.Error);
            }

            // Reauthorize the user. A browser should be opened, and the user should enter his or her credential again.
            await GoogleWebAuthorizationBroker.ReauthorizeAsync(credential, CancellationToken.None);

            // The request should succeed now.
            await ListLibrary(service);
        }
Beispiel #9
0
        public static async Task <string> RefreshAccessTokenAsync()
        {
            Log("Reauthorizing...");
            await GoogleWebAuthorizationBroker.ReauthorizeAsync(_credential, CancellationToken.None);

            Log("Refreshing token...");
            while (!(await _credential.RefreshTokenAsync(CancellationToken.None)))
            {
                Log("Failed to refresh token, retrying...");
            }
            Log("Creating service...");
            MyLogger.Assert(_driveService != null);
            _driveService.Dispose();
            _driveService = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = _credential,
                ApplicationName       = "Google Drive APIs",
            });
            Log("Service created!");
            MyLogger.Log($"Access token: {await GetAccessTokenAsync()}");
            return(await GetAccessTokenAsync());
        }
Beispiel #10
0
        public async Task Connect()
        {
            await Login();

            bool cookiesReceived = false;

            while (!cookiesReceived)
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
                var response = await client.GetAsync("https://accounts.google.com/accounts/OAuthLogin?source=hangups&issueuberauth=1");

                var responseText = await response.Content.ReadAsStringAsync();

                response = await client.GetAsync("https://accounts.google.com/MergeSession?service=mail&continue=http://www.google.com&uberauth=" + responseText);

                responseText = await response.Content.ReadAsStringAsync();

                IEnumerable <string> cookies;
                if (response.Headers.TryGetValues("set-cookie", out cookies))
                {
                    cookiesReceived = true;
                    foreach (var c in cookies)
                    {
                        cookieContainer.SetCookies(response.RequestMessage.RequestUri, c);
                        CookieUri = response.RequestMessage.RequestUri;
                    }
                }
                else
                {
                    Debug.WriteLine("No cookies received");
                    cookiesReceived = false;
                    CancellationToken token = new CancellationToken();
                    await GoogleWebAuthorizationBroker.ReauthorizeAsync(credential, token);
                }
            }

            listen();
        }
Beispiel #11
0
        /// <remarks>
        /// This has to be done here, since UserCredential cannot be used in CalDavSynchronizer,
        /// since it leads to a 'The "FindRibbons" task failed unexpectedly' Error
        /// ( see https://connect.microsoft.com/VisualStudio/feedback/details/651634/the-findribbons-task-failed-unexpectedly)
        /// </remarks>
        public static async Task <TasksService> LoginToGoogleTasksService(string user, IWebProxy proxyOrNull)
        {
            var credential = await LoginToGoogle(user, proxyOrNull);

            var service = CreateTaskService(credential, proxyOrNull);

            try
            {
                await service.Tasklists.List().ExecuteAsync();

                return(service);
            }
            catch (GoogleApiException x)
            {
                s_logger.Error("Trying to access google task service failed. Revoking  token and reauthorizing.", x);

                await credential.RevokeTokenAsync(CancellationToken.None);

                await GoogleWebAuthorizationBroker.ReauthorizeAsync(credential, CancellationToken.None);

                return(CreateTaskService(credential, proxyOrNull));
            }
        }
        public async Task Login(IEnumerable <ValidScopes> validScopes)
        {
            validScopes = validScopes.Distinct();
            var scopes = GoogleScopes.EnumToString(validScopes);

            var clientSecrets = new ClientSecrets()
            {
                ClientId = ConfigClientId, ClientSecret = ConfigClientSecret
            };

            if (!IsTokenSet || !Scopes.EnsureContains(validScopes))
            {
                Credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, scopes, "user", CancellationToken.None);

                Token = Credential.Token;
            }
            if (IsTokenSet && IsTokenExpired && IsRefreshTokenPresent)
            {
                await GoogleWebAuthorizationBroker.ReauthorizeAsync(Credential, CancellationToken.None);
            }


            Scopes = validScopes;
        }
Beispiel #13
0
 public async Task RefreshToken(UserCredential credenciais)
 => await GoogleWebAuthorizationBroker.ReauthorizeAsync(credenciais, CancellationToken.None);
 public async Task Reauthorize()
 {
     await GoogleWebAuthorizationBroker.ReauthorizeAsync(credential, CancellationToken.None);
 }