OAuth 2.0 (original) (raw)

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 Protocol

OAuth 2.0 is the authorization protocol used by Google APIs. You should get familiar with the protocol by reading the following links:

Acquire client IDs and secrets

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 shown (except the Service account one), you have to download the client secret and store it as client_secrets.json in your project.

Credentials

User credentials

UserCredential is a thread-safe helper class for using an access token to access protected resources. An access token typically expires after 1 hour, after which you will get an error if you try to use it.

UserCredential andAuthorizationCodeFlow take care of automatically "refreshing" the token, which means getting a new access token. This is done using a long-lived refresh token, which you receive along with the access token if you use theaccess_type=offline parameter during the authorization code flow.

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 ofIDataStore, or you can use one of the following implementations provided by the library:

ServiceAccountCredential

ServiceAccountCredential is similar to UserCredential, but it serves a different purpose. Google OAuth 2.0 supports server-to-server interactions such as those between a web application and Google Cloud Storage. The requesting application has to prove its own identity to gain access to an API, and an end user doesn't have to be involved.ServiceAccountCredential stores a private key, which is used to sign a request to get a new access token.

Both UserCredential and ServiceAccountCredential implementIConfigurableHttpClientInitializer so you can register each of these as:

Installed applications

Sample 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 { ///

/// Sample which demonstrates how to use the Books API. /// https://developers.google.com/books/docs/v1/getting_started /// 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-specificOpenIdConnect auth handler. It supports incremental auth, and defines an injectableIGoogleAuthProvider to supply Google credentials that can be used with Google APIs.

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 Startup class or similar alternative you might be using. The following snippets are extracted from Startup.cs in the Google.Apis.Auth.AspNetCore3.IntegrationTests project.

}

Use the user credential to access Google APIs on their behalf

You 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 HomeController.cs from the Google.Apis.Auth.AspNetCore3.IntegrationTests project to find out how you can achieve:

Service account

Google APIs also supportService 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 { ///

/// This sample demonstrates the simplest use case for a Service Account service. /// The certificate needs to be downloaded from the Google API Console /// /// "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". /// 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();
    }
}

}

This sample creates aServiceAccountCredential. The required scopes are set and there is a call to FromCertificate, which loads the private key from the given X509Certificate2. As in all other samples code, the credential is set as HttpClientInitializer.