public static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Tasks API"); // Register the authenticator. var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); provider.ClientIdentifier = credentials.ClientId; provider.ClientSecret = credentials.ClientSecret; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); // Create the service. var service = new TasksService(auth); // Execute request: Create sample list. if (!ListExists(service, SampleListName) && CommandLine.RequestUserChoice("Do you want to create a sample list?")) { CreateSampleTasklist(service); } CommandLine.WriteLine(); // Execute request: List task-lists. ListTaskLists(service); CommandLine.PressAnyKeyToExit(); }
private static IAuthenticator CreateAuthenticator() { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = ClientCredentials.ClientID; provider.ClientSecret = ClientCredentials.ClientSecret; return new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); }
private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = cacheFile; const string KEY = "y},drdzf11x9;87"; string scope = Google.Apis.Plus.v1.PlusService.Scopes.PlusMe.GetStringValue(); // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { ex.ShowError(); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; }
/// <summary> /// Return Analytics Service object /// </summary> /// <returns>Analytics Service object</returns> public static AnalyticsService GetAnalyticsService() { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = Settings.ClientIdentifier; provider.ClientSecret = Settings.ClientSecret; if (string.IsNullOrWhiteSpace(provider.ClientIdentifier)) { throw new Exception("Client identifier not found"); } if (string.IsNullOrWhiteSpace(provider.ClientSecret)) { throw new Exception("Client secret not found"); } string refreshToken = Settings.RefreshToken; if (string.IsNullOrWhiteSpace(refreshToken)) { throw new Exception("Refresh token not found"); } var request = HttpContext.Current.Request; var authenticator = new OAuth2Authenticator<NativeApplicationClient>(provider, (arg) => { IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/analytics.readonly" }); state.Callback = new Uri(string.Format("{0}://{1}{2}/GoogleAnalytics/Callback", request.Url.Scheme, request.Url.Host, request.Url.Port == 80 ? string.Empty : ":" + request.Url.Port)); state.RefreshToken = refreshToken; var result = arg.RefreshToken(state); return state; }); return new AnalyticsService(authenticator); }
private cGoogle() { // Register the authenticator. The Client ID and secret have to be copied from the API Access // tab on the Google APIs Console. provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = "528532804655.apps.googleusercontent.com"; provider.ClientSecret = "9QSFSAg0dE5CqC5F_Ot6MD8f"; // Get the auth URL: state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() }); state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl); Uri authUri = provider.RequestUserAuthorization(state); // Request authorization from the user (by opening a browser window): Process.Start(authUri.ToString()); // Initialize background workers authWorker = new BackgroundWorker(); fetchWorker = new BackgroundWorker(); authWorker.WorkerReportsProgress = true; authWorker.WorkerSupportsCancellation = true; authWorker.DoWork += new DoWorkEventHandler(authWorker_DoWork); authWorker.ProgressChanged += new ProgressChangedEventHandler(authWorker_ProgressChanged); fetchWorker.WorkerReportsProgress = true; fetchWorker.WorkerSupportsCancellation = true; fetchWorker.DoWork += new DoWorkEventHandler(fetchWorker_DoWork); fetchWorker.ProgressChanged += new ProgressChangedEventHandler(fetchWorker_ProgressChanged); }
public System.IO.Stream DownloadFile(string FileID, string CLIENT_ID, string CLIENT_SECRET, string ConnectionString) { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET); var authenticator = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); var service = new DriveService(authenticator); _ConnectionString = ConnectionString; File file = service.Files.Get(FileID).Fetch(); if (!String.IsNullOrEmpty(file.DownloadUrl)) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(file.DownloadUrl)); request.Headers.Set("Authorization", "Bearer " + authenticator.State.AccessToken.ToString()); authenticator.ApplyAuthenticationToRequest(request); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { return response.GetResponseStream(); } else { throw new Exception("An error occurred: " + response.StatusDescription); } } catch (Exception e) { throw new Exception("Downloading File Failed: " + e.Message); } } else { // The file doesn't have any content stored on Drive. return null; } }
private IAuthenticator CreateAuthenticator() { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = <myClientId>; provider.ClientSecret = <myClientSecret>"; return new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); }
private static IAuthorizationState GetAuthorization(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "latitude.client"; const string KEY = "45dfgvq2345"; // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; }
private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.analytics.xstat"; const string KEY = "=UwuqAtRaqe-3daV"; // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } string[] scopes = new string[] { "https://www.google.com/analytics/feeds/", "https://www.googleapis.com/auth/analytics.readonly" }; // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, scopes); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; }
private IAuthorizationState GetAuthorization(NativeApplicationClient arg) { // Get the auth URL: _state = new AuthorizationState(new[] {DriveService.Scopes.Drive.GetStringValue()}); _state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl); Uri authUri = arg.RequestUserAuthorization(_state); //Show Login UI. It's tip for user var dlg = new AuthDlg(StorageType.GDrive); dlg.Top = 0; dlg.Show(); // Request authorization from the user (by opening a browser window): //Process.Start(authUri.ToString()); _webViewCallback(authUri.ToString()); dlg.Close(); //close non-modal stub dialog //open another, modal dialog to block execution until user clicks OK dlg = new AuthDlg(StorageType.GDrive) {Top = 0}; dlg.ShowDialog(); // Retrieve the access token by using the authorization code: return arg.ProcessUserAuthorization(dlg.AuthCode, _state); }
public GoogleCalendar() { //UserCredential credential; //using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) //{ // //var clientSecrets = GoogleClientSecrets.Load(stream).Secrets; // credential = GoogleWebAuthorizationBroker.AuthorizeAsync( // stream, // new[] { CalendarService.Scope.Calendar }, // "user", CancellationToken.None, new FileDataStore("Calendar.ListMyLibrary")).Result; // service = new CalendarService(new BaseClientService.Initializer() // { // HttpClientInitializer = credential, // ApplicationName = "Outlook Google Sync" , // }); // //credential = authorizeAsync.Result; //} var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = "646754649922-g2p0157e4q3d5qv25ia3ur09vrc455k6.apps.googleusercontent.com"; provider.ClientSecret = "ZyPfCdrOFb6y-VWrdVZ65_8M"; service = new CalendarService(new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication)); service.Key = "AIzaSyCg7QtvUT6V3Hh3ZG7M5KfDiFScRkaYix0"; }
public void CheckForValidAccessTokenTest() { int accessTokenCounter = 1; var state = new AuthorizationState(); var client = new NativeApplicationClient(new Uri("http://example.com")); var auth = new OAuth2Authenticator<NativeApplicationClient>( client, (clt) => { // Load a "cached" access token. state.AccessToken = "token" + (accessTokenCounter++); return state; }); // Check that the initial state is null. Assert.IsNull(auth.State); // Check that the state was set when .LoadAccessToken() is called. auth.LoadAccessToken(); Assert.AreEqual(state, auth.State); Assert.AreEqual("token1", auth.State.AccessToken); // Check that it wont be set again. auth.LoadAccessToken(); Assert.AreEqual("token1", auth.State.AccessToken); // Check that it is set if our state gets invalid. state.AccessToken = null; auth.LoadAccessToken(); Assert.AreEqual("token2", auth.State.AccessToken); }
public IAuthorizationState GetAuthorization(Credentials credentials, string authCode) { var state = GetState(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, credentials.ClientID, credentials.ClientSecret); provider.ProcessUserAuthorization(authCode, state); return state; }
private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.prediction"; const string KEY = "AF41sdBra7ufra)VD:@#A#a++=3e"; string scope = PredictionService.Scopes.Prediction.GetStringValue(); // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; }
protected void Page_Load(object sender, EventArgs e) { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = "783795063122.apps.googleusercontent.com"; provider.ClientSecret = "_OQKo8_narny3sSrFcgCBWQV"; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); auth.LoadAccessToken(); }
static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("AdSense Management API Command Line Sample"); // Register the authenticator. var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); var credentials = PromptingClientCredentials.EnsureFullClientCredentials(); provider.ClientIdentifier = credentials.ClientId; provider.ClientSecret = credentials.ClientSecret; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. var service = new AdsenseService(auth); var accounts = GetAllAccounts.Run(service, MaxListPageSize); if (accounts.Items != null && accounts.Items.Count > 0) { // Get an example account ID, so we can run the following samples. var exampleAccountId = accounts.Items[0].Id; GetAccountTree.Run(service, exampleAccountId); GetAllAdClientsForAccount.Run(service, exampleAccountId, MaxListPageSize); } var adClients = GetAllAdClients.run(service, MaxListPageSize); if (adClients.Items != null && adClients.Items.Count > 0) { // Get an ad client ID, so we can run the rest of the samples. var exampleAdClientId = adClients.Items[0].Id; var adUnits = GetAllAdUnits.Run(service, exampleAdClientId, MaxListPageSize); if (adUnits.Items != null && adUnits.Items.Count > 0) { // Get an example ad unit ID, so we can run the following sample. var exampleAdUnitId = adUnits.Items[0].Id; GetAllCustomChannelsForAdUnit.Run(service, exampleAdClientId, exampleAdUnitId, MaxListPageSize); } var customChannels = GetAllCustomChannels.Run(service, exampleAdClientId, MaxListPageSize); if (customChannels.Items != null && customChannels.Items.Count > 0) { // Get an example custom channel ID, so we can run the following sample. var exampleCustomChannelId = customChannels.Items[0].Id; GetAllAdUnitsForCustomChannel.Run(service, exampleAdClientId, exampleCustomChannelId, MaxListPageSize); } GetAllUrlChannels.Run(service, exampleAdClientId, MaxListPageSize); GenerateReport.Run(service, exampleAdClientId); GenerateReportWithPaging.Run(service, exampleAdClientId, MaxReportPageSize); } CommandLine.PressAnyKeyToExit(); }
public static DriveService CreateDriveService() { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, Auth.ClientId, Auth.ClientSecret); var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); var service = new DriveService(new BaseClientService.Initializer() { Authenticator = auth }); return service; }
public void DelegateTest() { var state = new AuthorizationState() { AccessToken = "Test" }; var client = new NativeApplicationClient(new Uri("http://example.com")); var auth = new OAuth2Authenticator<NativeApplicationClient>(client, (clt) => state); // Check that the state was set. auth.LoadAccessToken(); Assert.AreEqual(state, auth.State); }
static void Main(string[] args) { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, Settings.Default.ClientId, Settings.Default.ClientSecret); var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); var driveService = new DriveService(new BaseClientService.Initializer() { Authenticator = auth }); driveService.Files.List().Fetch(); Console.ReadLine(); }
private static void Main(string[] args) { UtilArguments utilArguments = new UtilArguments(args); UtilAuthorization authorization = new UtilAuthorization(); File file = new File(); string clientID = ConfigurationManager.AppSettings["clientID"]; string clientSecret = ConfigurationManager.AppSettings["clientSecret"]; var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, clientID, clientSecret); var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, authorization.GetAuthorization); var service = new DriveService(auth); if (utilArguments["pub"] != null) { IServiceUploadDocument uploadDocument = new ServiceUploadDocument(new File()); file = uploadDocument.UploadDocument(service, @"www2net"); if (utilArguments["type"] != null) { file = uploadDocument.UploadDocument(service, @"www2net"); } } if (utilArguments["mkdir"] != null) { IServiceCreatePublicFolder serviceCreatePublicFolder = new ServiceCreatePublicFolder(new File(), new Permission()); string mkdir = utilArguments["mkdir"]; Console.WriteLine("Creating Public Shared Folder" + mkdir); file = serviceCreatePublicFolder.Mkdir(service, mkdir); IServiceUrlShortner serviceUrlShortner = new ServiceUrlShortner(new UrlshortenerService()); string uri = @"URL=" + serviceUrlShortner.Shorten("https://googledrive.com/host/" + file.Id); Console.WriteLine("Writting URL Shortcut to Desktop"); Console.WriteLine(uri); string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(path + "\\" + mkdir + ".url")) { streamWriter.WriteLine("[InternetShortcut]"); streamWriter.WriteLine(uri); streamWriter.Flush(); } } Console.WriteLine("File id: " + file.Id); Console.WriteLine("Press Enter to end this process."); Console.ReadLine(); }
public GDriveStorage(Action<string> webViewCallback) { _webViewCallback = webViewCallback; // Register the authenticator and create the service _nativeAppClient = new NativeApplicationClient(GoogleAuthenticationServer.Description, GOOGLE_DRIVE_CLIENT_ID, GOOGLE_DRIVE_CLIENT_SECRET); var auth = new OAuth2Authenticator<NativeApplicationClient>(_nativeAppClient, GetAuthorization); _service = new DriveService(auth); }
public void RequestUserAuthorizationTest() { var client = new NativeApplicationClient(GoogleAuthenticationServer.Description); client.ClientIdentifier = "Test"; client.ClientSecret = "123"; // Check that the callback URL is set correctly. We test this, as the Out of Band URI is required // for most cases of the Native-Application flow. Assert.IsTrue( client.RequestUserAuthorization().ToString().Contains(NativeApplicationClient.OutOfBandCallbackUrl)); }
public static GoogleAuthenticator GetAuthenticator(string authorizationCode) { var client = new NativeApplicationClient(GoogleAuthenticationServer.Description, _clientId, _clientSecret); IAuthorizationState state = new AuthorizationState() { Callback = new Uri(_redirectUri) }; state = client.ProcessUserAuthorization(authorizationCode, state); var auth = new OAuth2Authenticator<NativeApplicationClient>(client, (c) => state); auth.LoadAccessToken(); return new GoogleAuthenticator(auth); }
public void ApplyAuthenticationToRequestTest() { var request = (HttpWebRequest)WebRequest.Create("http://example.com"); var state = new AuthorizationState() { AccessToken = "Test" }; var client = new NativeApplicationClient(new Uri("http://example.com")); var auth = new OAuth2Authenticator<NativeApplicationClient>(client, (clt) => state); // Confirm that the request header gets modified. auth.ApplyAuthenticationToRequest(request); Assert.AreEqual(1, request.Headers.Count); }
/// <summary> /// Requests authorization on a native client by using a predefined set of authorization flows. /// </summary> /// <param name="client">The client used for authorization.</param> /// <param name="scopes">The requested set of scopes.</param> /// <returns>The authorized state.</returns> /// <exception cref="AuthenticationException">Thrown if the request was cancelled by the user.</exception> public static IAuthorizationState RequestNativeAuthorization(NativeApplicationClient client, params string[] scopes) { IAuthorizationState state = new AuthorizationState(scopes); string authCode = RequestNativeAuthorization(client, state); if (string.IsNullOrEmpty(authCode)) { throw new AuthenticationException("The authentication request was cancelled by the user."); } return client.ProcessUserAuthorization(authCode, state); }
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg) { // Get the auth URL: IAuthorizationState state = new AuthorizationState(new[] { DriveService.Scopes.Drive.GetStringValue() }); state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl); if (!String.IsNullOrWhiteSpace(RefreshToken)) { state.RefreshToken = RefreshToken; if (arg.RefreshToken(state)) return state; } return state; }
/// <summary> /// Requests authorization on a native client by using a predefined set of authorization flows. /// </summary> /// <param name="client">The client used for authentication.</param> /// <param name="authState">The requested authorization state.</param> /// <returns>The authorization code, or null if cancelled by the user.</returns> /// <exception cref="NotSupportedException">Thrown if no supported flow was found.</exception> public static string RequestNativeAuthorization(NativeApplicationClient client, IAuthorizationState authState) { // Try each available flow until we get an authorization / error. foreach (INativeAuthorizationFlow flow in NativeFlows) { try { return flow.RetrieveAuthorization(client, authState); } catch (NotSupportedException) { /* Flow unsupported on this environment */ } } throw new NotSupportedException("Found no supported native authorization flow."); }
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg) { // Get the auth URL: IAuthorizationState state = new AuthorizationState(new[] { TasksService.Scopes.Tasks.GetStringValue() }); state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl); Uri authUri = arg.RequestUserAuthorization(state); // Request authorization from the user (by opening a browser window): Process.Start(authUri.ToString()); Console.Write(" Authorization Code: "); string authCode = Console.ReadLine(); Console.WriteLine(); // Retrieve the access token by using the authorization code: return arg.ProcessUserAuthorization(authCode, state); }
static void Main(string[] args) { CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("YouTube Data API: My Uploads"); var credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); var youtube = new YoutubeService(new BaseClientService.Initializer() { Authenticator = auth }); var channelsListRequest = youtube.Channels.List("contentDetails"); channelsListRequest.Mine = true; var channelsListResponse = channelsListRequest.Fetch(); foreach (var channel in channelsListResponse.Items) { var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads; CommandLine.WriteLine(String.Format("Videos in list {0}", uploadsListId)); var nextPageToken = ""; while (nextPageToken != null) { var playlistItemsListRequest = youtube.PlaylistItems.List("snippet"); playlistItemsListRequest.PlaylistId = uploadsListId; playlistItemsListRequest.MaxResults = 50; playlistItemsListRequest.PageToken = nextPageToken; var playlistItemsListResponse = playlistItemsListRequest.Fetch(); foreach (var playlistItem in playlistItemsListResponse.Items) { CommandLine.WriteLine(String.Format("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId)); } nextPageToken = playlistItemsListResponse.NextPageToken; } } CommandLine.PressAnyKeyToExit(); }
public frmGoogleCal() { InitializeComponent(); // Register the authenticator. var cliCTCal = new NativeApplicationClient(GoogleAuthenticationServer.Description); cliCTCal.ClientIdentifier = "529290214236.apps.googleusercontent.com"; cliCTCal.ClientSecret = "4mdTMEEKuSCwGhPPxV9HfbtN"; var athCTCal = new OAuth2Authenticator<NativeApplicationClient>(cliCTCal, GetAuthorization); // Create the service. svcCTCal = new CalendarService(athCTCal); }