本文件說明 OAuth 2.0、使用時機、如何取得用戶端 ID,以及如何搭配 .NET 專用的 Google API 用戶端程式庫使用這項 API。
OAuth 2.0 通訊協定
OAuth 2.0 是 Google API 使用的授權通訊協定。建議您閱讀下列連結,熟悉這項通訊協定:
取得用戶端 ID 和密鑰
您可以在 Google API 控制台上取得用戶端 ID 和密鑰。用戶端 ID 有多種不同類型,因此請務必取得應用程式正確的類型:
在下列各個程式碼片段 (服務帳戶一個除外) 中,您必須下載用戶端密鑰,並將其儲存為 client_secrets.json
新增至專案中。
憑證
使用者憑證
UserCredential
是執行緒安全輔助類別,可使用存取權杖存取受保護的資源。存取權杖通常會在 1 小時後過期,如果嘗試使用該權杖,將會發生錯誤。
UserCredential
和 AuthorizationCodeFlow
會負責自動「重新整理」權杖,也就是取得新的存取權杖。方法是使用長效重新整理權杖;如果您在授權碼流程中使用 access_type=offline
參數,就會收到這組權杖。
在大多數應用程式中,建議將憑證的存取權杖和更新權杖儲存在永久儲存空間中。否則,您必須每小時向使用者在瀏覽器中提供授權頁面,因為存取權杖會在您收到的一小時後失效。
為確保存取權和重新整理權杖持續有效,您可以自行提供 IDataStore
實作,或使用下列其中一個程式庫提供的實作方式:
-
適用於 .NET 的
FileDataStore
可確保憑證永久保存在檔案中。
ServiceAccountCredential
ServiceAccountCredential
與 UserCredential
相似,但用途不同。Google OAuth 2.0 支援伺服器對伺服器的互動,例如網頁應用程式和 Google Cloud Storage 之間的互動。提出要求的應用程式必須證明自己的身分才能存取 API,使用者也不需要參與。
ServiceAccountCredential
會儲存私密金鑰,可用於簽署要求,以便取得新的存取權杖。
UserCredential
和 ServiceAccountCredential
都會實作 IConfigurableHttpClientInitializer
,因此您可以將這些項目註冊為:
- 失敗的回應處理常式,因此如果收到 HTTP
401
狀態碼,就會重新整理權杖。 - 攔截器,用於攔截每個要求的
Authorization
標頭。
應用程式已安裝
使用 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(); ... } } }
-
在這個程式碼範例中,系統會透過呼叫
GoogleWebAuthorizationBroker.AuthorizeAsync
方法建立新的UserCredential
例項。這個靜態方法會取得下列項目:- 用戶端密鑰 (或用戶端密鑰的串流)。
- 必要的範圍。
- 使用者 ID。
- 用於取消作業的取消權杖。
- 選用的資料儲存庫。如未指定資料儲存庫,則預設值為
FileDataStore
,且包含預設Google.Apis.Auth
資料夾。資料夾將建立於Environment.SpecialFolder.ApplicationData
。
-
此方法傳回的
UserCredential
會在BooksService
上設為HttpClientInitializer
(使用初始化器)。如上所述,UserCredential
會實作 HTTP 用戶端初始化器。 -
請注意,在上述程式碼範例中,用戶端密鑰資訊是從檔案載入,但您也可以執行下列操作:
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = "PUT_CLIENT_ID_HERE", ClientSecret = "PUT_CLIENT_SECRETS_HERE" }, new[] { BooksService.Scope.Books }, "user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
不妨參考我們的圖書範例。
網頁應用程式 (ASP.NET Core 3)
Google API 支援 網路伺服器應用程式適用的 OAuth 2.0。
在 ASP.NET Core 3 應用程式中,大多數 Google 式 OAuth 2.0 情境都建議使用
Google.Apis.Auth.AspNetCore3 程式庫。它會實作 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 Drive API,因此需要安裝 Google.Apis.Drive.v3 套件。
- 如果您還沒有 Google Cloud 專案,請建立一個。請按照 這些說明操作。這將是辨識應用程式的專案。
- 請務必啟用 Google Drive API。如要啟用 API,請按照 這些說明操作。
-
建立授權憑證,以便 Google 識別您的應用程式。請按照
這些操作說明建立授權憑證,並下載
client_secrets.json
檔案。以下兩點重點介紹:- 請注意,憑證類型必須是「網頁應用程式」。
- 如要執行這個應用程式,唯一需要新增的重新導向 URI 是
https://localhost:5001/signin-oidc
。
設定您的應用程式以使用 Google.Apis.Auth.AspNetCore3
Google.Apis.Auth.AspNetCore3 是在 Startup
類別中設定,或您可能正在使用的類似替代方案。下列程式碼片段是從 Google.Apis.Auth.AspNetCore3.IntegrationTests 專案中的
Startup.cs
擷取。
-
在
Startup.cs
檔案中加入下列指令。using Google.Apis.Auth.AspNetCore3;
-
在
Startup.ConfigureServices
方法中新增下列程式碼,標記用戶端 ID 和用戶端密鑰預留位置,也就是client_secrets.json
檔案中包含的值。您可以直接從 JSON 檔案載入這些值,也可以用任何其他安全的方式儲存這些值。查看 Google.Apis.Auth.AspNetCore3.IntegrationTests 專案中的ClientInfo.Load
方法,取得如何直接從 JSON 檔案載入這些值的範例。public void ConfigureServices(IServiceCollection services) { ... // This configures Google.Apis.Auth.AspNetCore3 for use in this app. services .AddAuthentication(o => { // This forces challenge results to be handled by Google OpenID Handler, so there's no // need to add an AccountController that emits challenges for Login. o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme; // This forces forbid results to be handled by Google OpenID Handler, which checks if // extra scopes are required and does automatic incremental auth. o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme; // Default scheme that will handle everything else. // Once a user is authenticated, the OAuth2 token info is stored in cookies. o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie() .AddGoogleOpenIdConnect(options => { options.ClientId = {YOUR_CLIENT_ID}; options.ClientSecret = {YOUR_CLIENT_SECRET}; }); }
-
在
Startup.Configure
方法中,請務必將 ASP.NET Core 3 驗證和授權中介軟體元件新增至管道,以及 HTTPS 重新導向:public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { ... app.UseHttpsRedirection(); ... app.UseAuthentication(); app.UseAuthorization(); ... }
透過使用者憑證,代表使用者存取 Google API
您現在可以為控制器新增動作方法,這些方法需要使用者憑證才能代表使用者存取 Google API。下列程式碼片段說明如何列出已驗證使用者的 Google 雲端硬碟帳戶中的檔案。主要有兩個要點:
-
使用者不僅需要通過驗證,還必須透過
GoogleScopedAuthorize
屬性指定為應用程式授予https://www.googleapis.com/auth/drive.readonly
範圍。 -
我們正在使用 ASP.NET Core 3 的標準依附元件插入機制接收用於取得使用者憑證的
IGoogleAuthProvider
。
程式碼:
-
首先,請使用指令將以下內容新增至控制器。
using Google.Apis.Auth.AspNetCore3; using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v3; using Google.Apis.Services;
-
新增控制器動作,如下所示 (並隨附接收
IList<string>
模型的簡易檢視區塊):/// <summary> /// Lists the authenticated user's Google Drive files. /// Specifying the <see cref="GoogleScopedAuthorizeAttribute"> will guarantee that the code /// executes only if the user is authenticated and has granted the scope specified in the attribute /// to this application. /// </summary> /// <param name="auth">The Google authorization provider. /// This can also be injected on the controller constructor.</param> [GoogleScopedAuthorize(DriveService.ScopeConstants.DriveReadonly)] public async Task<IActionResult> DriveFileList([FromServices] IGoogleAuthProvider auth) { GoogleCredential cred = await auth.GetCredentialAsync(); var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = cred }); var files = await service.Files.List().ExecuteAsync(); var fileNames = files.Files.Select(x => x.Name).ToList(); return View(fileNames); }
以上就是一些基本概念您可以透過 Google.Apis.Auth.AspNetCore3.IntegrationTests 專案查看
HomeController.cs
,瞭解如何達成以下目標:
- 僅限使用者驗證 (未設定特定範圍)
- 登出功能
- 透過程式碼逐步增加授權。請注意,上述程式碼片段透過屬性顯示漸進式授權。
- 檢查目前授予的範圍
- 檢查存取權並更新權杖
- 強制更新存取權杖。請注意,Google.Apis.Auth.AspNetCore3 會偵測存取權杖是否已過期或即將過期,因此您不必自行執行這項作業,因此您不需要自行執行這項作業。
服務帳戶
此外,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 { /// <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(); } } }
上述程式碼範例會建立 ServiceAccountCredential
。必要範圍已設定,並呼叫 FromCertificate
,可從指定的 X509Certificate2
載入私密金鑰。與其他所有程式碼範例一樣,憑證會設為 HttpClientInitializer
。