OAuth 2.0 credential for accessing protected resources using an access token, as well as optionally refreshing the access token when it expires using a refresh token.
Inheritance: IHttpExecuteInterceptor, IHttpUnsuccessfulResponseHandler, IConfigurableHttpClientInitializer
示例#1
1
        public static GmailService GetGmailService(UserCredential cr = null)
        {
            UserCredential credential = cr ?? GetGmailCredentials();

            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });
            return service;
        }
        public YouTubeService NewTestYouTubeService(string accessToken, string refreshToken)
        {
            var access_token = accessToken;
            var refresh_token = refreshToken;

            TokenResponse token = new TokenResponse
            {
                AccessToken = access_token,
                RefreshToken = refresh_token
            };

            var cred = new UserCredential
                (new GoogleAuthorizationCodeFlow(
                    new GoogleAuthorizationCodeFlow.Initializer()
                    {
                        ClientSecrets = new ClientSecrets()
                        {
                            ClientId = "//clientId",
                            ClientSecret = "//clientSecret"
                        }
                    }
                    ),
                    "testUser1",
                    token
                );

            return new YouTubeService(new BaseClientService.Initializer()
            {
                ApplicationName = this.GetType().ToString(),
                HttpClientInitializer = cred
            });
        }
示例#3
0
 private static async Task <Google.Apis.Drive.v3.DriveService> OpenService(Google.Apis.Auth.OAuth2.UserCredential credentials)
 {
     return(await Task.Run <Google.Apis.Drive.v3.DriveService>(() => new Google.Apis.Drive.v3.DriveService(new Google.Apis.Services.BaseClientService.Initializer()
     {
         HttpClientInitializer = credentials
     })));
 }
        private async void buttonLogin_Click(object sender, EventArgs e)
        {
            buttonLogin.Enabled = false;

            try
            {
                _cancellationTokenSource = new CancellationTokenSource();
                _userCredentials = await GoogleBloggerv3Client.GetOAuth2AuthorizationAsync(_blogId, _cancellationTokenSource.Token);
                _cancellationTokenSource = null;

                if (_userCredentials?.Token != null)
                {
                    // Leave the button disabled but let the user know they are signed in.
                    buttonLogin.Text = Res.Get(StringId.CWGoogleBloggerSignInSuccess);

                    // If this is the first time through the login flow, automatically click the 'Next' button on 
                    // behalf of the user.
                    if (_wizardController != null)
                    {
                        _wizardController.next();
                        _wizardController = null;
                    }
                }
            }
            finally
            {
                if (_userCredentials?.Token == null)
                {
                    // Let the user try again.
                    buttonLogin.Enabled = true;
                }
            }
        }
示例#5
0
        public ApiMethods()
        {
            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Calendar API service.
            service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = applicationName,
            });
        }
示例#6
0
 public void Disconnect()
 {
     IsAuthorized = false;
     _credential = null;
     _youtubeService.Dispose();
     _youtubeService = null;
 }
示例#7
0
        public void Login()
        {
            
            

           // creeaza si stocheaza obiectul credentiale
            using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart");
                Credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { DriveService.Scope.Drive},
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
            //    Directory.Delete(credPath, true);
            }

            //creeaza serviciul 
            Service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = Credential,
                ApplicationName = "Sorin Drive API",
            });

           

            
        }
        public async Task Authorize(string mailServer, int port , bool ssl, string login,string password)
        {
            if (ssl)
            {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        new ClientSecrets {
                             ClientId = "28442394418-7uqnmq187jlq53edfhhueebtb040grtk.apps.googleusercontent.com",
                              ClientSecret = "rgBZD9PjWvUAsU7IUjUcHnFy"
                        },
                        new[] { GmailService.Scope.GmailReadonly },
                        "user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));

                var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Gmail Scraper",
                });

                client.ConnectSsl(mailServer);
                client.Login(login, password);

                //Client.ConnectSsl(mailServer, port);
                //Client.Login(login, password);
            }
            else
            {
                client.ConnectSsl(mailServer);
                client.Login(login, password);
            }   
        }
        public AdexIntegration(string jsonpath)
        {
            using (var stream = new FileStream(jsonpath, FileMode.Open, FileAccess.Read))
            {
                OauthCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
                 GoogleClientSecrets.Load(stream).Secrets,
                 new[] { AdExchangeSellerService.Scope.AdexchangeSeller },
                  "user", CancellationToken.None, new FileDataStore("AdexchangeSeller.Auth.Store10")).Result;

            }


            Dimensions = new List<string>()
            {
            "DATE",
            "AD_TAG_CODE",
            "AD_TAG_NAME",
            "AD_UNIT_SIZE_CODE"
            };
            Metrics = new List<string>()
            {
                "MATCHED_AD_REQUESTS",
                "CLICKS",
                "MATCHED_AD_REQUESTS_CTR",
                "MATCHED_AD_REQUESTS_RPM",
                "EARNINGS",
                "AD_UNIT_SIZE_CODE",
                "AD_REQUESTS"
            };

        }
示例#10
0
        public async Task AuthenticateWithGoogle()
        {
            if (_googleCredential != null)
            {
                await _googleCredential.RefreshTokenAsync(CancellationToken.None);
            }
            else
            {
                using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    _googleCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        new[] { YouTubeService.Scope.Youtube },
                        "user",
                        CancellationToken.None,
                        new FileDataStore(StringConstants.ApplicationName));
                }
            }

            if (Service == null)
            {
                Service = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = _googleCredential,
                    ApplicationName = StringConstants.ApplicationName
                });
            }
        }
 public Google.Apis.Drive.v3.DriveService LoginComputerAccount(Google.Apis.Auth.OAuth2.UserCredential credenciais)
 {
     return(new Google.Apis.Drive.v3.DriveService(new Google.Apis.Services.BaseClientService.Initializer()
     {
         HttpClientInitializer = credenciais
     }));
 }
示例#12
0
        /// <summary>
        /// Create a new instance of a GoogleScriptApiService
        /// </summary>
        /// <param name="secretsFile">Path to the client_secret.json file downloaded from the Google developer console.</param>
        /// <param name="credStorePath">Path to the directory where you wish to store the credentials.</param>
        /// <param name="applicationName">Name of your application.</param>
        /// <param name="projectKey">Project key of the script you wish to invoke.</param>
        /// <param name="functionName">Name of the script function you wish to invoke.</param>
        /// <param name="neededScopes">The set of Scopes required for your application.</param>
        /// <exception cref="ArgumentNullException">Any parameter was null.</exception>
        /// <exception cref="FileNotFoundException">Parameter <see cref="secretsFile" /> was not found or not a file.</exception>
        /// <exception cref="DirectoryNotFoundException">Parameter <see cref="credStorePath" /> was not found or not a directory.</exception>
        public GoogleScriptApiService(
            string secretsFile,
            string credStorePath,
            string applicationName,
            string projectKey,
            string functionName,
            string[] neededScopes)
        {
            if (secretsFile == null) throw new ArgumentNullException(nameof(secretsFile));
            if (credStorePath == null) throw new ArgumentNullException(nameof(credStorePath));

            if (!File.Exists(secretsFile)) throw new FileNotFoundException(nameof(secretsFile));
            if (!Directory.Exists(credStorePath)) throw new DirectoryNotFoundException(nameof(credStorePath));

            if (projectKey == null) throw new ArgumentNullException(nameof(projectKey));
            if (applicationName == null) throw new ArgumentNullException(nameof(applicationName));
            if (functionName == null) throw new ArgumentNullException(nameof(functionName));
            if (neededScopes == null) throw new ArgumentNullException(nameof(neededScopes));
            
            _projectKey = projectKey;
            _appName = applicationName;
            _funcName = functionName;
            _scopes = neededScopes;

            using (Stream sr = new FileStream(secretsFile, FileMode.Open, FileAccess.Read))
            {
                _credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(sr).Secrets,
                    _scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credStorePath, fullPath: true)).GetAwaiter().GetResult();
            }
        }
        private DriveService _CreateService()
        {
            var tokenResponse = new TokenResponse
            {
                AccessToken  = _config.AccessToken,
                RefreshToken = _config.RefreshToken,
            };

            var apiCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId     = _config.ClientId,
                    ClientSecret = _config.ClientSecret
                },
                Scopes    = new[] { DriveService.Scope.Drive },
                DataStore = new FileDataStore(_config.AppName)
            });

            var credential = new Google.Apis.Auth.OAuth2.UserCredential(apiCodeFlow, _config.UserName, tokenResponse);

            var service = new DriveService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = _config.AppName
            });

            return(service);
        }
示例#14
0
文件: DataService.cs 项目: roosi/done
 public void SetUserCredential(UserCredential credential)
 {
     _service = new TasksService(new BaseClientService.Initializer()
     {
         HttpClientInitializer = credential,
         ApplicationName = _application
     });
 }
 /// <summary>
 /// Asynchronously reauthorizes the user. This method should be called if the users want to authorize after 
 /// they revoked the token.
 /// </summary>
 /// <param name="userCredential">The current user credential. Its <see cref="UserCredential.Token"/> will be
 /// updated. </param>
 /// <param name="taskCancellationToken">Cancellation token to cancel an operation.</param>
 public static async Task ReauthorizeAsync(UserCredential userCredential,
     CancellationToken taskCancellationToken)
 {
     var installedApp = new AuthorizationCodeWindowsInstalledApp(userCredential.Flow);
     // Create an authorization code installed app instance and authorize the user.
     UserCredential newUserCredential = await installedApp.AuthorizeAsync(
         userCredential.UserId, taskCancellationToken).ConfigureAwait(false);
     userCredential.Token = newUserCredential.Token;
 }
示例#16
0
 public static BloggerService createService(UserCredential uc, string appName)
 {
     BloggerService bs = new BloggerService(new BaseClientService.Initializer
         {
             HttpClientInitializer = uc,
             ApplicationName = appName
         });
     return bs;
 }
		public static GmailService GetService(UserCredential credential)
		{
			// Create Gmail Service.
			return new GmailService(new BaseClientService.Initializer()
			{
				HttpClientInitializer = credential,
				ApplicationName = ApplicationName
			});
		}
        public async Task ConnectAsync()
        {
            if(IsConnected) {
                await DisconnectAsync().ConfigureAwait(false);
            }

            Logger.Info("Connecting to Google Services...");

            try {
                ClientSecrets secrets;
                using(Stream stream = new FileStream("C:/EnergonSoftware/google_play_client_secrets.json", FileMode.Open, FileAccess.Read)) {
                    secrets = GoogleClientSecrets.Load(stream).Secrets;
                }

                if(null == secrets) {
                    Logger.Error("Failed to read client secrets!");
                    return;
                }

                _userCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    secrets,
                    new[] {
                        DriveService.Scope.DriveFile,
                        "https://www.googleapis.com/auth/drive.appfolder"
                    },
                    Properties.Settings.Default.GooglePlayServicesUser,
                    CancellationToken.None,
                    new FileDataStore("EnergonSoftware.DriveFileExplorer.Auth.Store")).ConfigureAwait(false);
                if(null == _userCredential) {
                    Logger.Error("Failed to create user credentials!");
                    return;
                }

                Properties.Settings.Default.GooglePlayServicesUser = _userCredential.UserId;

                _driveService = new DriveService(
                    new BaseClientService.Initializer
                    {
                        HttpClientInitializer = _userCredential,
                        ApplicationName = "Backpacking Planner"
                    }
                );

                Logger.Info("Connected!");
                NotifyPropertyChanged("IsConnected");
                NotifyPropertyChanged("IsNotConnected");
            } catch(Exception ex) {
                Logger.Error($"Error connecting to Google Services: {ex.Message}", ex);

                Cleanup();

                NotifyPropertyChanged("IsConnected");
                NotifyPropertyChanged("IsNotConnected");
            }
        }
        public async Task<UserCredential> GetUserCredential()
        {
            _credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                _clientSecretsPath,
                new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeReadonly, YouTubeService.Scope.YoutubeForceSsl },
                "user",
                CancellationToken.None
                );

            return _credential;
        }
示例#20
0
        public static bool SendMail(string fromMail, string[] toMails, string message, string title, UserCredential cr = null)
        {
            var service = GetGmailService(cr);
            var request = service.Users.Messages.List("me");
            var msg = new Message();
            string body = "To: " + String.Join(",", toMails) + "\n" +
                          "Subject: " + title + "\n\n" + message;
            msg.Raw = EncodeTo64(body);
            var send = service.Users.Messages.Send(msg, fromMail);

            send.Execute();
            return true;
        }
示例#21
0
        public GoogleDriveService()
        {
            this.scopes = new string[] { DriveService.Scope.Drive };

            this.credential = GetCredentialWithAccessToken(refreshToken, clientId, clientSecret, scopes);
            this.credential.Token.Issued = DateTime.Now;

            this.instance = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = this.credential,
                ApplicationName = Assemblies.ApplicationName,
            });
        }
		public static void DeleteAllUnreadMessages()
		{
			Credential = Preparation.GetUserCredential();

			var messages = Messages.ListMessages(Preparation.GetService(Credential), User, "in:inbox is:unread");

			if (!messages.Any()) 
				return;

			foreach (var message in messages)
			{
				Messages.DeleteMessage(Service, User, message.Id);
			}
		}
示例#23
0
 public static void authorize(string authpath)
 {
     using (var stream = new FileStream(authpath, FileMode.Open, FileAccess.Read))
     {
         string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
         credPath = Path.Combine(credPath, "seminar");
         credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
             GoogleClientSecrets.Load(stream).Secrets,
             Scopes,
             "user",
             CancellationToken.None,
             new FileDataStore(credPath, true)).Result;
     }
 }
        public void Authenticate()
        {
            // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
            {
                ClientId = clientId,
                ClientSecret = clientSecret
            }, scopes, userName, CancellationToken.None).Result;
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "BloggerApp",
            };

            service = new BloggerService(initializer);
        }
        private void EnsureService()
        {
            if (!_setting.UseGoogleDrive)
            {
                return;
            }

            if (_driveService != null)
            {
                return;
            }

            if (string.IsNullOrEmpty(_setting.GoogleClientId) || string.IsNullOrEmpty(_setting.GoogleClientSecret) ||
                 string.IsNullOrEmpty(_setting.GoogleRefreshToken))
            {
                throw new ApplicationException("Missing google drive configuration");
            }

            try
            {
                var initializer = new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = _setting.GoogleClientId,
                        ClientSecret = _setting.GoogleClientSecret
                    }
                };
                var flow = new AuthorizationCodeFlow(initializer);
                //flow.RefreshTokenAsync("user", Configuration.GoogleRefreshToken, new CancellationTokenSource().Token);

                var tokenResponse = new TokenResponse { RefreshToken = _setting.GoogleRefreshToken };
                var userCredential = new UserCredential(flow, _setting.GoogleLocalUserId, tokenResponse);

                _driveService = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = userCredential,
                    ApplicationName = "Jarboo.Admin"
                });
            }
            catch (Exception ex)
            {
                _driveService = null;

                throw;
            }
        }
示例#26
0
        static XGCalendarAccess()
        {
            _credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
                {
                    ClientId = "1042911101976-hacnki3op1itrlogb9q2h7ttp2di8tp4.apps.googleusercontent.com",
                    ClientSecret = "RCUEZbs6-71Au7PyONONl8FD",
                },
                new[] { CalendarService.Scope.Calendar },
                "*****@*****.**",
                CancellationToken.None).Result;

            _calService = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = _credential,
                ApplicationName = "fruitybrewproject",
            });
        }
示例#27
0
        /// <summary>
        /// Function refreshes the token and update "this" object. Note it does not try to persist the authentication to permanent storage on azure. If you want it to persist call function refreshAndCommitToken;
        /// </summary>
        /// <returns></returns>
        public async Task <bool> refreshAuthenticationToken()
        {
            Google.Apis.Auth.OAuth2.UserCredential OldCredentials = getGoogleOauthCredentials();
            System.Threading.CancellationToken     CancelToken    = new System.Threading.CancellationToken();
            bool refreshSuccess = await OldCredentials.RefreshTokenAsync(CancelToken).ConfigureAwait(false);

            if (refreshSuccess)
            {
                this.ID           = OldCredentials.UserId;
                this.Token        = OldCredentials.Token.AccessToken;
                this.RefreshToken = OldCredentials.Token.RefreshToken;
                double   totalSeconds = OldCredentials.Token.ExpiresInSeconds == null ? 0 : (double)OldCredentials.Token.ExpiresInSeconds;
                DateTime myDate       = OldCredentials.Token.Issued.AddSeconds(totalSeconds);
                this.Deadline = new DateTimeOffset(myDate);
            }

            return(refreshSuccess);
        }
示例#28
0
        public static async Task<DriveService> GetClient(TokenResponse token)
        {
            var credentials = new UserCredential(
               AuthFlow,
               null,
               token);

            var driveInitializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = credentials,
                HttpClientFactory = new GoogleDriveHttpClientFactory(),
                ApplicationName = "KeeAnywhere",
            };

            var client = new DriveService(driveInitializer);

            return client;
        }
示例#29
0
        /// <summary>
        /// function generates the google oauth credentials
        /// </summary>
        /// <returns></returns>
        public Google.Apis.Auth.OAuth2.UserCredential getGoogleOauthCredentials()
        {
            Google.Apis.Auth.OAuth2.Responses.TokenResponse responseData = new Google.Apis.Auth.OAuth2.Responses.TokenResponse();
            responseData.AccessToken  = this.Token;
            responseData.RefreshToken = this.RefreshToken;
            GoogleAuthorizationCodeFlow.Initializer myInit         = new GoogleAuthorizationCodeFlow.Initializer();
            AuthorizationCodeFlow.Initializer       codeFlowIntial = myInit;
            codeFlowIntial.ClientSecrets = new ClientSecrets();
            string googleClientId     = ConfigurationManager.AppSettings["googleClientId"];
            string googleClientSecret = ConfigurationManager.AppSettings["googleClientSecret"];

            codeFlowIntial.ClientSecrets.ClientId     = googleClientId;
            codeFlowIntial.ClientSecrets.ClientSecret = googleClientSecret;
            IAuthorizationCodeFlow myFlow = AppFlowMetadata.getFlow();

            Google.Apis.Auth.OAuth2.UserCredential RetValue = new Google.Apis.Auth.OAuth2.UserCredential(myFlow, this.ID, responseData);
            return(RetValue);
        }
示例#30
0
        /// <summary>
        /// The user authorizes the app and his credentials are saved on a .json file
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static UserCredential GetGoogleOAuthCredential(string user, string jsonpath)
        {
            String JsonFilelocation = jsonpath;

            Google.Apis.Auth.OAuth2.UserCredential credential = null;
            using (var stream = new FileStream(JsonFilelocation, FileMode.Open,
                                               FileAccess.Read))
            {
                Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.Folder = "Tasks.Auth.Store";
                credential = Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(
                    Google.Apis.Auth.OAuth2.GoogleClientSecrets.Load(stream).Secrets,
                    new[] { DriveService.Scope.Drive, PlusService.Scope.UserinfoProfile, PlusService.Scope.UserinfoEmail },
                    user,
                    System.Threading.CancellationToken.None,
                    new FileDataStore("Drive.Auth.Store")).Result;
            }
            crede = credential;
            return(credential);
        }
        private async Task AuthenticateAsync()
        {
            if (service != null)
                return;

            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new Uri("ms-appx:///Assets/client_secrets.json"),
                new[] { BloggerService.Scope.BloggerReadonly },
                "user",
                CancellationToken.None);

            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "BloggerApp",
            };

            service = new BloggerService(initializer);
        }
        public override async Task ConnectAsync()
        {
            if(IsConnected) {
                Logger.Info("Google API already connected!");
                OnConnected(new PlayServicesConnectedEventArgs { IsSuccess= true });
                return;
            }

            Logger.Info("Connecting Google Play Services client...");

            try {
                _userCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new Uri("ms-appx:///Assets/google_play_client_secrets.json"),
                    new[] {
                        DriveService.Scope.DriveFile,
                        "https://www.googleapis.com/auth/drive.appfolder"
                    },
                    App.CurrentApp.BackpackPlannerState.Settings.GooglePlayServicesUser,
                    CancellationToken.None).ConfigureAwait(false);
                if(null == _userCredential) {
                    OnConnected(new PlayServicesConnectedEventArgs { IsSuccess = false });
                    return;
                }

                App.CurrentApp.BackpackPlannerState.Settings.GooglePlayServicesUser = _userCredential.UserId;

                _driveService = new DriveService(
                    new BaseClientService.Initializer
                    {
                        HttpClientInitializer = _userCredential,
                        ApplicationName = "Backpacking Planner"
                    }
                );

                OnConnected(new PlayServicesConnectedEventArgs { IsSuccess = true });
            } catch(Exception ex) {
                Logger.Error($"Error connecting to Google Services: {ex.Message}", ex);

                Cleanup();

                OnConnected(new PlayServicesConnectedEventArgs { IsSuccess = false });
            }
        }
        private async Task AuthenticateAsync()
        {
            if (_service != null)
                return;

            _credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new Uri("ms-appx:///Assets/client_secrets.json"),
                new[] { Oauth2Service.Scope.UserinfoEmail },
                "user",
                CancellationToken.None);

            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = _credential,
                ApplicationName = "GoogleLogin",
            };

            _service = new Oauth2Service(initializer);

        }
    public GoogleDriveDownloader()
    {
        IEnumerable<string> lines = System.IO.File.ReadLines("C:\\Users\\OneBox\\Documents\\Google.txt");
        this.credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            new ClientSecrets
            {
                ClientId = lines.ElementAt(0),
                ClientSecret = lines.ElementAt(1),
            },
            new[] { DriveService.Scope.Drive },
            "user",
            CancellationToken.None).Result;

        // Create the service.
        this.service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "OneBox",
        });
    }
 /// <summary>
 /// Authorize using OAuth2.0 with Google API using Web
 /// User won't be redirected to the app so need to close the browser/tab.
 /// </summary>
 /// <param name="smartMirrorUsername"></param>
 /// <param name="gesture"></param>
 /// <returns></returns>
 private async Task AuthorizeUsingWeb(string smartMirrorUsername, string gesture)
 {
     try
     {
         UserCredential credential;
         using (var stream = new FileStream(GoogleClientSecretFileLocation, FileMode.Open, FileAccess.Read))
         {
             credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                 GoogleClientSecrets.Load(stream).Secrets,
                 new[] { CalendarService.Scope.Calendar, GmailService.Scope.GmailReadonly, GmailService.Scope.MailGoogleCom, PlusService.Scope.PlusMe },
                 smartMirrorUsername, CancellationToken.None, new FileDataStore(DataStoreLocation));
         }
         SetCurrentUser(ParseUserCredentials(credential, smartMirrorUsername, gesture));
         _currentUserCredential = credential;
     }
     catch (Exception error)
     {
         Debug.WriteLine(error);
     }
 }
 public static UserCredential GetUserCredential(out string error)
 {
     Google.Apis.Auth.OAuth2.UserCredential credential = null;
     error = string.Empty;
     try
     {
         credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
             new ClientSecrets
         {
             ClientId     = ClientId,
             ClientSecret = ClientSecret
         },
             Scopes,
             Environment.UserName,
             CancellationToken.None,
             new FileDataStore("Google Oauth2 Client App")).Result;
     }
     catch (Exception ex)
     {
         credential = null;
         error      = "Failed to UserCredential Initialization : " + ex.ToString();
     }
     return(credential);
 }
示例#37
0
        async public Task <ActionResult> ImportGoogle(CancellationToken cancellationToken)
        {
            string UserID = User.Identity.GetUserId();
            //var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata(UserID)).
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);

            Google.Apis.Auth.OAuth2.UserCredential myCredential = result.Credential;



            if (myCredential != null)
            {
                var service = new Oauth2Service(new BaseClientService.Initializer
                {
                    HttpClientInitializer = myCredential,
                    ApplicationName       = "ASP.NET MVC Sample"
                });

                bool ResetThirdparty = false;

                ThirdPartyCalendarAuthenticationModel thirdpartydata = new ThirdPartyCalendarAuthenticationModel();
                Google.Apis.Oauth2.v2.Data.Userinfo   userInfo;
                try
                {
                    userInfo = service.Userinfo.Get().Execute();
                }
                catch (Exception e)
                {
                    ResetThirdparty = true;
                    return(RedirectToAction("ImportGoogle"));
                }



                string Email = userInfo.Email;

                if (myCredential.Token.RefreshToken != null)  //if user hasn't authenticated tiler before
                {
                    thirdpartydata.Email       = Email;
                    thirdpartydata.TilerID     = UserID;
                    thirdpartydata.ID          = myCredential.UserId;
                    thirdpartydata.isLongLived = false;
                    double   totalSeconds = myCredential.Token.ExpiresInSeconds == null ? 0 : (double)myCredential.Token.ExpiresInSeconds;
                    DateTime myDate       = myCredential.Token.Issued.AddSeconds(totalSeconds);
                    thirdpartydata.Deadline     = new DateTimeOffset(myDate);
                    thirdpartydata.ProviderID   = TilerElements.ThirdPartyControl.CalendarTool.google.ToString();
                    thirdpartydata.Token        = myCredential.Token.AccessToken;
                    thirdpartydata.RefreshToken = myCredential.Token.RefreshToken;

                    return(await CreateGoogle(thirdpartydata).ConfigureAwait(false));
                }
                else     //if user hasn authenticated tiler before, then update current credentials
                {
                    ThirdPartyCalendarAuthenticationModel retrievedAuthentication = await getGoogleAuthenticationData(UserID, Email).ConfigureAwait(false);

                    try
                    {
                        await retrievedAuthentication.refreshAndCommitToken(dbContext).ConfigureAwait(false);
                    }
                    catch
                    {
                        if (retrievedAuthentication != null)
                        {
                            deleteGoogleAccount(retrievedAuthentication.getThirdPartyOut()).RunSynchronously();
                        }
                        else if (myCredential.Token != null)
                        {
                            thirdpartydata.Email       = Email;
                            thirdpartydata.TilerID     = UserID;
                            thirdpartydata.ID          = myCredential.UserId;
                            thirdpartydata.isLongLived = false;
                            double   totalSeconds = myCredential.Token.ExpiresInSeconds == null ? 0 : (double)myCredential.Token.ExpiresInSeconds;
                            DateTime myDate       = myCredential.Token.IssuedUtc.AddSeconds(totalSeconds);
                            thirdpartydata.Deadline     = new DateTimeOffset(myDate);
                            thirdpartydata.ProviderID   = TilerElements.ThirdPartyControl.CalendarTool.google.ToString();
                            thirdpartydata.Token        = myCredential.Token.AccessToken;
                            thirdpartydata.RefreshToken = myCredential.Token.RefreshToken;
                            await thirdpartydata.unCommitAuthentication().ConfigureAwait(false);

                            return(await ImportGoogle(cancellationToken).ConfigureAwait(false));
                        }
                    }

                    return(RedirectToAction("ImportCalendar"));
                }
            }
            else
            {
                //return View();
                return(new RedirectResult(result.RedirectUri));
            }
        }
 private async void OnCircle(bool clockwise)
 {
     if (clockwise)
         _curentUserCredential = await GoogleSignin("Tjarda");
     else
         _curentUserCredential = await GoogleSignin("Rinesh");
 }