OAuth 2.0 (original) (raw)

本文件將說明 OAuth 2.0、使用時機、取得用戶端 ID 的方式,以及如何搭配 .NET 適用的 Google API 用戶端程式庫使用。

OAuth 2.0 通訊協定

OAuth 2.0 是 Google API 使用的授權通訊協定。請參閱下列連結,熟悉這個通訊協定:

取得用戶端 ID 和密鑰

您可以在 Google API 控制台取得用戶端 ID 和密鑰。 用戶端 ID 有不同類型,因此請務必取得應用程式所需的正確類型:

在每個顯示的程式碼片段中 (服務帳戶除外),您都必須下載用戶端密鑰,並將其儲存在專案中,做為 client_secrets.json

憑證

使用者憑證

UserCredential 是執行緒安全的輔助程式類別,可用來使用存取權存取金鑰存取受保護的資源。存取權杖通常會在 1 小時後過期,之後若嘗試使用此權杖將會出現錯誤。

UserCredentialAuthorizationCodeFlow 會自動「重新整理」憑證,也就是取得新的存取憑證。這項作業會使用長期有效的更新權杖完成,如果您在授權碼流程中使用 access_type=offline 參數,系統會隨存取權杖一併傳送這項權杖。

在大多數應用程式中,建議您將憑證的存取權杖和重新整理權杖儲存在永久性儲存空間中。否則,您必須每小時在瀏覽器中向使用者顯示授權頁面,因為存取權存證記號會在收到後一小時過期。

為確保存取權和重新整理權杖持續存在,您可以提供自己的 IDataStore 實作項目,也可以使用程式庫提供的下列任一實作項目:

ServiceAccountCredential

ServiceAccountCredentialUserCredential 類似,但用途不同。Google OAuth 2.0 支援伺服器對伺服器的互動行為,例如網頁應用程式和 Google Cloud Storage 之間的互動。發出要求的應用程式必須證明其身分才能存取 API,而且使用者不需要採取任何行動。ServiceAccountCredential 會儲存私密金鑰,用於簽署要求以取得新的存取權存取權杖。

UserCredentialServiceAccountCredential 都實作 IConfigurableHttpClientInitializer,因此您可以將這兩者註冊為:

已安裝的應用程式

使用 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();
        ...
    }
}

}

請參考我們的書籍範例

網頁應用程式 (ASP.NET Core 3)

Google API 支援 針對網路伺服器應用程式使用 OAuth 2.0

在 ASP.NET Core 3 應用程式中, Google.Apis.Auth.AspNetCore3 是建議用於大多數 Google 架構 OAuth 2.0 情境的程式庫。實作 Google 專屬的 OpenIdConnect 驗證處理常式。它支援漸進式驗證,並定義可供注入的 IGoogleAuthProvider,以提供可與 Google API 搭配使用的 Google 憑證。

本節說明如何設定及使用 Google.Apis.Auth.AspNetCore3。這裡顯示的程式碼是根據 Google.Apis.Auth.AspNetCore3.IntegrationTests 所提供的標準 ASP.NET Core 3 應用程式,這也是完整運作的應用程式。

如果您想按照本說明文件中的教學課程操作,則必須先完成下列步驟,並使用自己的 ASP.NET Core 3 應用程式。

必要條件

將應用程式設為使用 Google.Apis.Auth.AspNetCore3

Google.Apis.Auth.AspNetCore3 會在 Startup 類別或您可能使用的類似替代方案中設定。以下程式碼片段是從 Google.Apis.Auth.AspNetCore3.IntegrationTests 專案的 Startup.cs 中擷取。

}

使用使用者憑證代表使用者存取 Google API

您現在可以為控制器新增動作方法,這些方法需要使用者憑證才能代替使用者存取 Google API。以下程式碼片段示範如何在已驗證的使用者 Google 雲端硬碟帳戶中列出檔案。請注意以下兩點:

程式碼:

這些都是基本概念。您可以查看 Google.Apis.Auth.AspNetCore3.IntegrationTests 專案中的 HomeController.cs,瞭解如何達成以下目標:

服務帳戶

Google API 也支援服務帳戶。與用戶端應用程式要求存取使用者資料的情況不同,服務帳戶會提供用戶端應用程式自身資料的存取權。

用戶端應用程式會使用從 Google API 控制台下載的私密金鑰,為存取權存證要求簽署。建立新的用戶端 ID 後,請選擇服務帳戶應用程式類型,然後即可下載私密金鑰。請參閱 使用 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();
    }
}

}

這個範例會建立 ServiceAccountCredential。設定必要的範圍,並呼叫 FromCertificate,從指定的 X509Certificate2 載入私密金鑰。如同其他範例程式碼,憑證會設為 HttpClientInitializer