This document describes OAuth 2.0, when to use it, how to acquire client IDs, and how to use it with the Google API Client Library for .NET. OAuth 2.0 is the authorization protocol used by Google APIs. You should get familiar with the protocol by reading the following links: You can get client IDs and secrets on the Google API Console. There are different types of client IDs, so
be sure to get the correct type for your application: In each of the code snippets
below (except the Service account one), you have to download the client secret and store it as In most applications, it is advisable to store the credential's access token and refresh token in persistent storage. Otherwise, you will need to present the end user with an authorization page in the browser every hour, because the access token expires an hour after you've received it. To make sure the access and refresh tokens persist, you can provide your own implementation of
ServiceAccountCredential Both
Installed applicationsSample code using the Books API: using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Google.Apis.Auth.OAuth2; using Google.Apis.Books.v1; using Google.Apis.Books.v1.Data; using Google.Apis.Services; using Google.Apis.Util.Store; namespace Books.ListMyLibrary { /// <summary> /// Sample which demonstrates how to use the Books API. /// https://developers.google.com/books/docs/v1/getting_started /// <summary> internal class Program { [STAThread] static void Main(string[] args) { Console.WriteLine("Books API Sample: List MyLibrary"); Console.WriteLine("================================"); try { new Program().Run().Wait(); } catch (AggregateException ex) { foreach (var e in ex.InnerExceptions) { Console.WriteLine("ERROR: " + e.Message); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } private async Task Run() { UserCredential credential; using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { BooksService.Scope.Books }, "user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary")); } // Create the service. var service = new BooksService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Books API Sample", }); var bookshelves = await service.Mylibrary.Bookshelves.List().ExecuteAsync(); ... } } }
Take a look at our Books sample. Web applications (ASP.NET Core 3)Google APIs support OAuth 2.0 for Web Server Applications. The Google.Apis.Auth.AspNetCore3 is the recommended library to use for most Google based OAuth 2.0 scenarios in ASP.NET Core 3 applications. It implements a Google-specific This section describes how to configure and use Google.Apis.Auth.AspNetCore3. The code shown here is based on Google.Apis.Auth.AspNetCore3.IntegrationTests which is a fully working, standard ASP.NET Core 3 application. If you want to follow along this documentation as a tutorial, you will need your own ASP.NET Core 3 application and to complete these steps as a prerequisite. Prerequisites
Configure your application to use Google.Apis.Auth.AspNetCore3 Google.Apis.Auth.AspNetCore3 is configured in the
Use the user credential to access Google APIs on their behalfYou are now ready to add action methods to your controllers that require the user credential to access Google APIs on their behalf. The following snippet shows how to list the files on the authenticated user's Google Drive account. Notice two things mostly:
The code:
And these are the basics. You can take a look at
Web applications (ASP.NET MVC) Google APIs support OAuth 2.0 for Web Server Applications. In order to run the following code successfully, you must first add a redirect URI to your project in the
Google API Console. Since you will use To find the redirect URIs for your OAuth 2.0 credentials, do the following:
After creating a new web application project in your IDE, add the right
Service accountGoogle APIs also support Service accounts. Unlike the scenario in which a client application requests access to an end-user's data, service accounts provide access to the client application's own data. Your client application signs the request for an access token using a private key downloaded from the Google API Console. After creating a new client ID, you should choose a “Service Account” application type and then you can download the private key. Take a look at our service account sample using Google Plus API. using System; using System.Security.Cryptography.X509Certificates; using Google.Apis.Auth.OAuth2; using Google.Apis.Plus.v1; using Google.Apis.Plus.v1.Data; using Google.Apis.Services; namespace Google.Apis.Samples.PlusServiceAccount { /// <summary> /// This sample demonstrates the simplest use case for a Service Account service. /// The certificate needs to be downloaded from the Google API Console /// <see cref="https://console.cloud.google.com/"> /// "Create another client ID..." -> "Service Account" -> Download the certificate, /// rename it as "key.p12" and add it to the project. Don't forget to change the Build action /// to "Content" and the Copy to Output Directory to "Copy if newer". /// </summary> public class Program { // A known public activity. private static String ACTIVITY_ID = "z12gtjhq3qn2xxl2o224exwiqruvtda0i"; public static void Main(string[] args) { Console.WriteLine("Plus API - Service Account"); Console.WriteLine("=========================="); String serviceAccountEmail = "SERVICE_ACCOUNT_EMAIL_HERE"; var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { PlusService.Scope.PlusMe } }.FromCertificate(certificate)); // Create the service. var service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Plus API Sample", }); Activity activity = service.Activities.Get(ACTIVITY_ID).Execute(); Console.WriteLine(" Activity: " + activity.Object.Content); Console.WriteLine(" Video: " + activity.Object.Attachments[0].Url); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } } The above sample code creates a |