public new static async Task<UserCredential> AuthorizeAsync(ClientSecrets clientSecrets, IEnumerable<string> scopes, string user, CancellationToken taskCancellationToken, IDataStore dataStore = null) { var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = clientSecrets, }; return await AuthorizeAsyncCore(initializer, scopes, user, taskCancellationToken, dataStore) .ConfigureAwait(false); }
/// <summary>Asynchronously authorizes the specified user.</summary> /// <remarks> /// It uses <seealso cref="Google.Apis.Util.Store.StroageDataStore"/> as the flow's data store by default. /// </remarks> /// <param name="clientSecrets">The client secrets URI.</param> /// <param name="scopes"> /// The scopes which indicate the Google API access your application is requesting. /// </param> /// <param name="user">The user to authorize.</param> /// <param name="taskCancellationToken">Cancellation token to cancel an operation.</param> /// <returns>User credential.</returns> private static async Task<UserCredential> AuthorizeAsync(ClientSecrets clientSecrets, IEnumerable<string> scopes, string user, CancellationToken taskCancellationToken) { var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = clientSecrets, Scopes = scopes, DataStore = new StroageDataStore() }; var installedApp = new AuthorizationCodeWinRTInstalledApp(initializer); return await installedApp.AuthorizeAsync(user, taskCancellationToken).ConfigureAwait(false); }
static GoogleDriveHelper() { var flowInitializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = GoogleDriveClientId, ClientSecret = GoogleDriveClientSecret }, Scopes = Scopes, HttpClientFactory = new GoogleDriveHttpClientFactory() }; AuthFlow = new GoogleAuthorizationCodeFlow(flowInitializer); }
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; } }
public void GoogleAuthorizationCodeFlowTestSetup() { string revokeTokenUrl = "Revoke Token Url"; bool? includeGrantedScopes = true; userDefinedParams = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("customParam1","customVal1"), new KeyValuePair<string,string>("customParam2","customVal2") }; initializer = new GoogleAuthorizationCodeFlow.Initializer() { RevokeTokenUrl = revokeTokenUrl, IncludeGrantedScopes = includeGrantedScopes, UserDefinedQueryParams = userDefinedParams, ClientSecrets = new ClientSecrets() }; }
private async Task<UserCredential> GetCredentialForApiAsync() { var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = MyClientSecrets.ClientId, ClientSecret = MyClientSecrets.ClientSecret, }, Scopes = MyRequestedScopes.Scopes, }; var flow = new GoogleAuthorizationCodeFlow(initializer); var identity = await HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync( DefaultAuthenticationTypes.ApplicationCookie); var userId = identity.FindFirstValue(MyClaimTypes.GoogleUserId); var token = await dataStore.GetAsync<TokenResponse>(userId); return new UserCredential(flow, userId, token); }
private static async Task<UserCredential> LoginToGoogle (string user, IWebProxy proxyOrNull) { GoogleAuthorizationCodeFlow.Initializer initializer = new GoogleAuthorizationCodeFlow.Initializer(); initializer.ClientSecrets = CreateClientSecrets(); initializer.HttpClientFactory = new ProxySupportedHttpClientFactory (proxyOrNull); UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync ( initializer, new[] { "https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/carddav", "https://www.googleapis.com/auth/tasks", "https://www.google.com/m8/feeds/" // => contacts }, user, CancellationToken.None); return credential; }
/// <summary>Creates a user credential from JSON data.</summary> private static UserCredential CreateUserCredentialFromJson(JsonCredentialParameters credentialParameters) { if (credentialParameters.Type != JsonCredentialParameters.AuthorizedUserCredentialType || string.IsNullOrEmpty(credentialParameters.ClientId) || string.IsNullOrEmpty(credentialParameters.ClientSecret)) { throw new InvalidOperationException("JSON data does not represent a valid user credential."); } var token = new TokenResponse { RefreshToken = credentialParameters.RefreshToken }; var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = credentialParameters.ClientId, ClientSecret = credentialParameters.ClientSecret } }; var flow = new GoogleAuthorizationCodeFlow(initializer); return new UserCredential(flow, "ApplicationDefaultCredentials", token); }
private static void Run() { UserCredential credential; var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = new[] { PlusService.Scope.PlusLogin } }; var flow = new AAGoogleAuthorizationCodeFlow(initializer); credential = new AuthorizationCodeInstalledApp(flow, new LocalServerCodeReceiver()).AuthorizeAsync ("user", CancellationToken.None).Result; // Create the service. var service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Gus API", }); Moment body = new Moment(); ItemScope target = new ItemScope(); target.Url = "https://developers.google.com/+/web/snippet/examples/widget"; target.Image = "http://picpaste.com/pics/001.1437292069.jpg"; //target.Type = "http://schema.org/Thing"; target.Description = "The description for the action"; target.Name = "An example of add activity"; body.Target = target; body.Type = "http://schemas.google.com/AddActivity"; //PeopleResource.GetRequest personRequest = service.People.Get("me"); //Person _me = personRequest.Execute(); MomentsResource.InsertRequest insert = service.Moments.Insert(body, "me", MomentsResource.InsertRequest.CollectionEnum.Vault); //new MomentsResource.InsertRequest( // service, // body, // "me", // MomentsResource.InsertRequest.CollectionEnum.Vault); Moment wrote = insert.Execute(); MomentsResource.ListRequest ls = service.Moments.List("me", MomentsResource.ListRequest.CollectionEnum.Vault); MomentsFeed feeds = ls.Execute(); }
public AppFlowMetadata(string applicationPath, string googleCredentialsJson) { try { GoogleClientJson googleClientJson = GoogleClientJson.Load(googleCredentialsJson); var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = googleClientJson.Web.ClientId, ClientSecret = googleClientJson.Web.ClientSecret }, Scopes = new[] {CalendarService.Scope.Calendar}, DataStore = new FileDataStore(applicationPath, FileDataStoreFolder) }; _flow = new GoogleAuthorizationCodeFlow(initializer); _googleUserId = googleClientJson.Web.ClientEmail; Valid = true; } catch (Exception e) { Logger.SetLog(e); Valid = false; } }
private static async Task<UserCredential> SAuthorizeAsync(string user, CancellationToken token) { Stream stream; try { using (stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MailChecker.Resources.clientsecrets.json")) { var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecretsStream = stream, }; initializer.Scopes = new[] { "https://mail.google.com" }; var flow = new GoogleAuthorizationCodeFlow(initializer); return await new AuthorizationCodeInstalledApp(flow, new LocalServerCodeReceiver()).AuthorizeAsync (user, token).ConfigureAwait(false); } } catch (Exception e) { logging.TraceEvent(TraceEventType.Error, 1, "Error in SAuthorizeAsync: " + e); return null; } }
private DriveService CreateDriveService(GoogleCredentials googleCredentials) { var authorizationCodeFlowInitializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = googleCredentials.ClientId, ClientSecret = googleCredentials.ClientSecret } }; var googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow(authorizationCodeFlowInitializer); var token = new TokenResponse { RefreshToken = googleCredentials.RefreshToken }; var credentials = new UserCredential(googleAuthorizationCodeFlow, "user", token); var initializer = new BaseClientService.Initializer { ApplicationName = "Emby", HttpClientInitializer = credentials }; return new DriveService(initializer) { HttpClient = { Timeout = TimeSpan.FromHours(1) } }; }
/// <summary> /// 로그인 처리를 위한 초기설정을 도와주는 함수 /// </summary> /// <param name="client">Client_id와 Client_Secret이 담겨있는 클래스(구글 드라이브 콘솔에서 발급받은 id와 비밀번호)</param> /// <param name="scopes">접근 권한에 대한 주소값들이 들어있는 List</param> /// <param name="username">사용자를 구별하기 위한 닉네임</param> /// <param name="taskCancellationToken">작업이 취소되지 않아야 함을 나타내는 값 : None으로 표시</param> /// <param name="store">저장할 위치 (경로로 표시 : 기본 위치 -> C:\Users\bit-user\AppData\Roaming) </param> /// initializer는 클라이언트 id와 클라이언트 시크릿 번호를 설정해준다. /// <returns>반환값은 유저의 정보가 담긴 UserCredential 클래스 반환</returns> /// public static async Task<UserCredential> LoginAuthorizationCodeFlowAsync(ClientSecrets client, IEnumerable<string> scopes, string username, CancellationToken taskCancellationToken, FileDataStore store) { var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = client, }; return await AuthorizeAsyncCore(initializer, scopes, username, taskCancellationToken, store) .ConfigureAwait(false); }
/// <summary>Asynchronously authorizes the specified user.</summary> /// <remarks> /// It uses <see cref="Google.Apis.Util.Store.StorageDataStore"/> as the flow's data store by default. /// </remarks> /// <param name="clientSecretsStream"> /// The client secrets stream. The AuthorizationCodeFlow constructor is responsible for disposing the stream. /// Note that it's more secured to use the authenticate method which gets <see cref="ClientSecrets"/>, and /// hard code your secrets in your app rather than storing the secrets in a separate unsecured file. /// </param> /// <param name="scopes"> /// The scopes which indicate the Google API access your application is requesting. /// </param> /// <param name="user">The user to authorize.</param> /// <param name="taskCancellationToken">Cancellation token to cancel an operation.</param> /// <returns>User credential.</returns> public static async Task<UserCredential> AuthorizeAsync(Stream clientSecretsStream, IEnumerable<string> scopes, string user, CancellationToken taskCancellationToken) { var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecretsStream = clientSecretsStream, }; return await AuthorizeAsyncCore(initializer, scopes, user, taskCancellationToken).ConfigureAwait(false); }
/// <summary>Asynchronously authorizes the specified user.</summary> /// <remarks> /// It uses <seealso cref="Google.Apis.Util.Store.StorageDataStore"/> as the flow's data store by default. /// </remarks> /// <param name="clientSecrets">The client secrets.</param> /// <param name="scopes"> /// The scopes which indicate the Google API access your application is requesting. /// </param> /// <param name="user">The user to authorize.</param> /// <param name="taskCancellationToken">Cancellation token to cancel an operation.</param> /// <returns>User credential.</returns> public static async Task<UserCredential> AuthorizeAsync(ClientSecrets clientSecrets, IEnumerable<string> scopes, string user, CancellationToken taskCancellationToken) { var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = clientSecrets, }; return await AuthorizeAsyncCore(initializer, scopes, user, taskCancellationToken); }
public async Task<bool> ManualAccountAuthetication(string accountName, CancellationToken cancellationToken, Func<Task<string>> getCodeDeledateFunc) { try { var applicationDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.None); var fullPath = applicationDataPath + @"\PCoMD\" + Constants.AuthFolderPath; var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = Constants.ClientId, ClientSecret = Constants.ClientSecret }, Scopes = GetScopes(), DataStore = new FileDataStore(fullPath, true) }; var authTask = await new AuthorizationCodeInstalledApp( new GoogleAuthorizationCodeFlow(initializer), new CustomCodeReceiver(getCodeDeledateFunc)) .AuthorizeAsync(String.Format("-{0}-googletoken", accountName), CancellationToken.None); var service = new CalendarService(new BaseClientService.Initializer { HttpClientInitializer = authTask, ApplicationName = ApplicationInfo.ProductName }); return true; } catch (AggregateException exception) { Logger.Error(exception); } catch (Exception exception) { Logger.Error(exception); } return false; }