Using Google APIs from Console apps in .NET
I have noticed a common and recent issue that developers have been having with the Google APIs has been building out console apps. In this post I’ll give you a few short demos for API calls and authorization. The following screenshot shows the token verification demo running from the console:
Running the Demo Solution / Projects
The demo for these console apps is available from my GitHub account. To clone the project from your console, just run:
git clone https://github.com/gguuss/google-dotnet-demo
From your GitHub shell.
After you have cloned the project, open the solution file, GoogleDotNetDemo.sln. Right click on the solution, select restore NuGet packages, and then press F5 to try running the apps. If everything worked correctly, the app should build and you will see the default app, the token verification demo, start running.
Demo of Simple API Calls: Token Verification from Console
The first example I’m going to show is a console app that performs Google OAuth 2 token verification. This is the most concise demo I could come up with and it’s actually useful if you want to check your access tokens during debugging.
First, set up your project from the NuGet package manager interface in Visual Studio, add Google.Apis.Oauth2.v2.
The following code is the full source of the app’s main function:
private static void Main(string[] args) { Console.WriteLine(@"Input an Access token:"); String accessToken = Console.ReadLine(); Oauth2Service service = new Oauth2Service( new Google.Apis.Services.BaseClientService.Initializer()); Oauth2Service.TokeninfoRequest request = service.Tokeninfo(); request.AccessToken = accessToken; Tokeninfo info = request.Execute(); Console.Write(@"Scope: " + info.Scope + "n"); Console.WriteLine(@"Expires: " + info.ExpiresIn); Console.ReadLine(); }
To make the API call, I’m just getting a service object for OAuth 2, constructing the request, adding the token, and finally executing the request.
Demo of Authorization: Get Google+ Profile information
In this demo, the user is authorized and then their profile information is retrieved and displayed.
First, as before, we’ll enable the required Google API client package, Google.Apis.Plus.v1. This will install additional client library dependencies.
The following is the full source of the main function:
// These come from the APIs console: // https://code.google.com/apis/console public static ClientSecrets secrets = new ClientSecrets() { ClientId = "YOUR_CLIENT_ID", ClientSecret = "YOUR_CLIENT_SECRET" }; static void Main(string[] args) { Console.WriteLine(@"Starting authorization..."); UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( secrets, new[] { PlusService.Scope.PlusLogin }, "me", CancellationToken.None).Result; // Create the service. var plusService = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Console Google+ Demo", }); Person me = plusService.People.Get("me").Execute(); Console.Write(@"Authorized user: " + me.DisplayName + "n"); Console.Write(@"Press enter to exit."); Console.Read(); }
You construct your credentials object with parameters from the Developer API console, authorize the user to get your credential, create your service object from the credential, and then can make your API calls with the service object.
Closing thoughts
Authorizing the user from the console is pretty easy. Note that doing so with the web browser is necessary because the user must input their credentials on the Google OAuth server.
More information can be found at:
- Using Google OAuth 2 to access Google APIs
- OAuth 2 flows in .NET
- ASP.NET MVC With Google OpenID and OAuth 2.0
for Demo of Authorization every time i get Error: redirect_uri_mismatch, and the port id different every time
Never imagined that it would be so hard to get user’s goddamn email. I dealt with all kinds of authorizations, but this is something beyond. Really google, time to wake up
Alex, sorry you’re having an issue here, you can alternatively try using a JavaScript solution and getting it client-side. Example here: http://wheresgus.com/emaildemo/
Thanks, may be a bit later
Hi Gus, sorry for complaining, as i said in stackoverflow, I understood how to get email. There are still some minor issues that i submitted on github
Anyway you guys rock 🙂
No worries, I totally understand. We try our best to make it a great developer experience and it can be frustrating when things seem broken. Good luck!
ahhhhhhh I’m having the same random port issue! At first i tried to create it as a web application and thought that was the problem. Even after setting a static port with the web application its something with the new web window that pops up. I created a new console app and its the same problem! I’m thinking its something to do with the HTTPClientInitializer . . .
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
Maybe there is a way in the initializer to set a static port