public static GmailService InitilzeServiceByServiceAccount() { try { var json = System.IO.File.ReadAllText(_serviceAccountKey); var cred = JsonConvert.DeserializeObject <ServiceAccountCred>(json); GmailService service = new GmailService(); var saCredential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cred.client_email) { Scopes = new[] { GmailService.Scope.GmailModify }, User = _serviceAccountUser }.FromPrivateKey(cred.private_key)); if (saCredential.RequestAccessTokenAsync(CancellationToken.None).Result) { var initilizer = new BaseClientService.Initializer() { HttpClientInitializer = saCredential, }; Google.Apis.Auth.OAuth2.Responses.TokenResponse toke = saCredential.Token; service = new GmailService(initilizer); } return(service); } catch (Exception ex) { Console.WriteLine("An error occurred: " + ex.Message); return(null); } }
public void RequestService() { var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse() { AccessToken = accessToken, RefreshToken = refreshToken, ExpiresInSeconds = expires, IssuedUtc = issuedDate }; var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret } }); UserCredential credential = new UserCredential(flow, "user", token); service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "XamarinCalendar", }); }
/// <summary> /// Uses hard coded info to authenticate and return credentials /// Note: All of the parameters required for this method can be /// retrieved from the JSON File and the cache file from the /// Prompt() method above /// </summary> /// <returns>Authentication object for API Requests</returns> public static IConfigurableHttpClientInitializer RefreshToken() { var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse { RefreshToken = ExamplesConfig.RefreshToken }; return new UserCredential(new GoogleAuthorizationCodeFlow( new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = ExamplesConfig.ClientId, ClientSecret = ExamplesConfig.ClientSecret }, }), "user", token); }
/// <summary> /// Returns the stored value for the given key or <c>null</c> if the matching file (<see cref="GenerateStoredKey"/> /// in <see cref="FolderPath"/> doesn't exist. /// </summary> /// <typeparam name="T">The type to retrieve</typeparam> /// <param name="key">The key to retrieve from the data store</param> /// <returns>The stored object</returns> public Task <T> GetAsync <T>(string key) { //Key is the user string sent with AuthorizeAsync if (string.IsNullOrEmpty(key)) { throw new ArgumentException("Key MUST have a value"); } Google.Apis.Auth.OAuth2.Responses.TokenResponse test = new Google.Apis.Auth.OAuth2.Responses.TokenResponse(); test.RefreshToken = @"1/mZ1edKKACtPAb7zGlwSzvs72PvhAbGmB8K1ZrGxpcNM"; var obj = NewtonsoftJsonSerializer.Instance.Serialize(test); var x = NewtonsoftJsonSerializer.Instance.Deserialize <T>(obj); TaskCompletionSource <T> tcs = new TaskCompletionSource <T>(); var io = GenerateStoredKey(key, typeof(T)); var filePath = Path.Combine(folderPath, GenerateStoredKey(key, typeof(T))); if (File.Exists(filePath)) { try { //var obj = File.ReadAllText(filePath); //var x = NewtonsoftJsonSerializer.Instance.Deserialize<T>(obj); tcs.SetResult(x); } catch (Exception ex) { tcs.SetException(ex); } } else { tcs.SetResult(default(T)); } return(tcs.Task); }
/// <summary> /// Uses hard coded info to authenticate and return credentials. /// Note: All of the parameters required for this method can be retrieved from the JSON /// File and the cache file from the Prompt() method above. /// </summary> /// <returns>Authentication object for API Requests</returns> public static IConfigurableHttpClientInitializer RefreshToken() { var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse { RefreshToken = ExamplesConfig.RefreshToken }; return(new UserCredential(new GoogleAuthorizationCodeFlow( new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = ExamplesConfig.ClientId, ClientSecret = ExamplesConfig.ClientSecret }, }), "user", token)); }
/// <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); }
public static UserCredential GetGoogleUserCredentialByRefreshToken(string refreshToken, out string error) { Google.Apis.Auth.OAuth2.Responses.TokenResponse respnseToken = null; UserCredential credential = null; string flowError; error = string.Empty; try { // Get a new IAuthorizationCodeFlow instance IAuthorizationCodeFlow flow = GoogleAuthorizationCodeFlow(out flowError); respnseToken = new Google.Apis.Auth.OAuth2.Responses.TokenResponse() { RefreshToken = refreshToken }; // Get a new Credential instance if ((flow != null && string.IsNullOrWhiteSpace(flowError)) && respnseToken != null) { credential = new UserCredential(flow, "user", respnseToken); } // Get a new Token instance if (credential != null) { bool success = credential.RefreshTokenAsync(CancellationToken.None).Result; } // Set the new Token instance if (credential.Token != null) { string newRefreshToken = credential.Token.RefreshToken; } } catch (Exception ex) { credential = null; error = "UserCredential failed: " + ex.ToString(); } return(credential); }
public static UserCredential GetUserCredential() { var localSettings = ApplicationData.Current.LocalSettings; var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse() { AccessToken = localSettings.Values["authToken"].ToString(), RefreshToken = localSettings.Values["refreshToken"].ToString(), ExpiresInSeconds = 3600, IssuedUtc = DateTime.Now }; var fakeflow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = YouTubeApiClientId } }); var credential = new UserCredential(fakeflow, "blahblah", token); return(credential); }
public async Task Authenticate(GoogleDriveAccount acc) { object threadlock = new Object(); GoogleAuthorizationCodeFlow.Initializer init = new GoogleAuthorizationCodeFlow.Initializer(); init.ClientSecrets = new ClientSecrets(); init.ClientSecrets.ClientId = AppInfo.GoogleClientId; init.ClientSecrets.ClientSecret = AppInfo.GoogleClientSecret; GoogleAuthorizationCodeFlow f = new GoogleAuthorizationCodeFlow(init); Google.Apis.Auth.OAuth2.Responses.TokenResponse t = null; UserCredential credential = new UserCredential(f, acc.UserId, acc.UserToken); await credential.RefreshTokenAsync(CancellationToken.None); driveService = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "SilentBackup", }); }
public JsonResult GetGoogleSession(string google_access_token, string google_refresh_token) { var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse() { AccessToken = google_access_token, RefreshToken = google_refresh_token, ExpiresInSeconds = 3600 }; var fakeflow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = "900082198060-kdvsjc3ecm82gn48dl9083cg0gihggm1.apps.googleusercontent.com", ClientSecret = "i1EN7mH7usgONgINmnNKbOFi" } }); UserCredential credential = new UserCredential(fakeflow, "fakeid", token); var serviceInitializer = new BaseClientService.Initializer() { ApplicationName = "LINCD-Blockchain", HttpClientInitializer = credential }; DriveService service = new DriveService(serviceInitializer); FilesResource.ListRequest request = service.Files.List(); request.PageSize = 100; request.PrettyPrint = true; request.Q = "'root' in parents and trashed = false"; request.Fields = @"files(*)"; IList <Google.Apis.Drive.v3.Data.File> files = request.Execute().Files; Content[] list = new Content[files.Count]; for (int i = 0; i < files.Count; i++) { list[i] = new Content(files[i].Kind, files[i].Id, files[i].Name, files[i].Size.ToString(), files[i].Md5Checksum, files[i].ModifiedTime.ToString(), "false"); } return(Json(list)); }
//TODO: Revise this to call on separate methods that fit with the rest of the consumer. /// <summary>Set the token and scope info all at once.</summary> public void SetTokenAndScopes(string Domain, string UserName, string Api, string TokenString, Google.Apis.Auth.OAuth2.Responses.TokenResponse TokenResponse, List <string> Scopes) { if (!UserExists(Domain, UserName)) { SetUser(Domain, new OAuth2DomainUser() { userName = UserName, domain = Domain }); } info.domains[Domain].users[UserName].tokenAndScopesByApi[Api] = new OAuth2TokenInfo(Scopes, TokenString, TokenResponse); dataStore.SaveInfo(info); }