OAuth 2.0

เอกสารนี้จะอธิบายเกี่ยวกับ OAuth 2.0, วิธีใช้, วิธีรับรหัสไคลเอ็นต์ และวิธีใช้งานกับไลบรารีของไคลเอ็นต์ Google API สําหรับ .NET

โปรโตคอล OAuth 2.0

OAuth 2.0 เป็นโปรโตคอลการให้สิทธิ์ที่ Google API ใช้ คุณควรทําความคุ้นเคยกับโปรโตคอลนี้โดยการอ่านลิงก์ต่อไปนี้

การได้รหัสไคลเอ็นต์และข้อมูลลับ

คุณจะรับรหัสไคลเอ็นต์และข้อมูลลับได้ในคอนโซล Google API รหัสไคลเอ็นต์มีหลายประเภท ดังนั้นโปรดตรวจสอบประเภทของแอปพลิเคชันที่ถูกต้องดังนี้

ในข้อมูลโค้ดแต่ละรายการด้านล่าง (ยกเว้นบัญชีบริการ 1 รายการ) คุณต้องดาวน์โหลดรหัสลับไคลเอ็นต์และจัดเก็บไว้เป็น client_secrets.json ในโปรเจ็กต์

ข้อมูลเข้าสู่ระบบ

ข้อมูลเข้าสู่ระบบของผู้ใช้

UserCredential เป็นคลาสของตัวช่วยป้องกันไม่ให้ชุดข้อความใช้โทเค็นเพื่อการเข้าถึงเพื่อเข้าถึงทรัพยากรที่มีการป้องกัน โดยทั่วไป โทเค็นเพื่อการเข้าถึงจะหมดอายุหลังจากผ่านไป 1 ชั่วโมง หลังจากนั้นคุณจะได้รับข้อผิดพลาดหากพยายามใช้

UserCredential และ AuthorizationCodeFlow ดูแล "Refreshing" โทเค็นโดยอัตโนมัติ ซึ่งหมายถึงการขอรับโทเค็นเพื่อการเข้าถึงใหม่ ซึ่งทําได้โดยใช้โทเค็นการรีเฟรชที่ใช้ได้นาน ซึ่งคุณจะได้รับมาพร้อมกับโทเค็นเพื่อการเข้าถึงหากคุณใช้พารามิเตอร์ access_type=offline ระหว่างขั้นตอนการให้สิทธิ์รหัสการให้สิทธิ์

ในแอปพลิเคชันส่วนใหญ่ ขอแนะนําให้จัดเก็บโทเค็นเพื่อการเข้าถึงและโทเค็นการรีเฟรชของข้อมูลเข้าสู่ระบบไว้ในพื้นที่เก็บข้อมูลถาวร มิฉะนั้น คุณจะต้องแสดงหน้าการให้สิทธิ์ในเบราว์เซอร์แก่ผู้ใช้ปลายทางทุกชั่วโมง เนื่องจากโทเค็นเพื่อการเข้าถึงจะหมดอายุภายใน 1 ชั่วโมงหลังจากที่คุณได้รับ

หากต้องการตรวจสอบว่าโทเค็นเพื่อการเข้าถึงและการรีเฟรชยังคงอยู่ ให้จัดเตรียม IDataStore ด้วยตัวเอง หรือใช้งานแบบใดแบบหนึ่งต่อไปนี้โดยไลบรารี

  • FileDataStore สําหรับ .NET จะช่วยให้แน่ใจว่าข้อมูลเข้าสู่ระบบจะยังคงอยู่ในไฟล์

ข้อมูลเข้าสู่ระบบบัญชีบริการ

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();
            ...
        }
    }
}
  
  • ในโค้ดตัวอย่างนี้ ระบบจะสร้างอินสแตนซ์ UserCredential ใหม่โดยการเรียกใช้เมธอด GoogleWebAuthorizationBroker.AuthorizeAsync วิธีแบบคงที่นี้ได้รับสิ่งต่อไปนี้

    • รหัสลับไคลเอ็นต์ (หรือสตรีมไปยังรหัสลับไคลเอ็นต์)
    • ขอบเขตที่จําเป็น
    • ตัวระบุผู้ใช้
    • โทเค็นการยกเลิกสําหรับการยกเลิกการดําเนินการ
    • พื้นที่เก็บข้อมูลที่ไม่บังคับ หากไม่ได้ระบุพื้นที่เก็บข้อมูล ค่าเริ่มต้นคือ FileDataStore ที่มีโฟลเดอร์ Google.Apis.Auth เริ่มต้น โฟลเดอร์นี้จะสร้างขึ้นใน Environment.SpecialFolder.ApplicationData
  • UserCredential ที่แสดงโดยเมธอดนี้เป็น HttpClientInitializer ใน BooksService (ใช้ตัวเริ่มต้น) ตามที่อธิบายไว้ข้างต้น 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 APIs รองรับ OAuth 2.0 สําหรับแอปพลิเคชันเว็บเซิร์ฟเวอร์

Google.Apis.Auth.AspNetCore3 เป็นไลบรารีที่แนะนําสําหรับการใช้งานในสถานการณ์ OAuth 2.0 ส่วนใหญ่ของ Google ในแอปพลิเคชัน ASP.NET Core 3 โดยจะใช้งานเครื่องจัดการการตรวจสอบสิทธิ์ OpenIdConnect เฉพาะสําหรับ Google รองรับการตรวจสอบสิทธิ์ที่เพิ่มขึ้นและกําหนด IGoogleAuthProvider ที่แทรกได้เพื่อระบุข้อมูลเข้าสู่ระบบของ Google ที่ใช้กับ Google APIs ได้

ส่วนนี้จะอธิบายวิธีการกําหนดค่าและใช้ 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 ไฮไลต์ 2 รายการต่อไปนี้
    • โปรดสังเกตว่าข้อมูลเข้าสู่ระบบ&#39 ประเภท ต้องเป็นเว็บแอปพลิเคชัน
    • สําหรับการเรียกใช้แอปนี้ URI การเปลี่ยนเส้นทางเดียวที่คุณต้องเพิ่มคือ https://localhost:5001/signin-oidc

กําหนดค่าแอปพลิเคชันให้ใช้ Google.Apis.Auth.AspNetCore3

Google.Apis.Auth.AspNetCore3 ได้รับการกําหนดค่าในคลาส Startup หรือทางเลือกที่คล้ายกันที่คุณอาจใช้อยู่ ข้อมูลโค้ดต่อไปนี้ดึงมาจาก Startup.cs ในโปรเจ็กต์ Google.Apis.Auth.AspNetCore3.IntegrationTests

  • เพิ่มคําสั่งต่อไปนี้ลงในไฟล์ Startup.cs
    using Google.Apis.Auth.AspNetCore3;
  • ในเมธอด Startup.ConfigureServices ให้เพิ่มโค้ดต่อไปนี้ เปลี่ยนค่ารหัสไคลเอ็นต์และตัวยึดตําแหน่งของรหัสลับไคลเอ็นต์ด้วยค่าที่อยู่ในไฟล์ client_secrets.json คุณจะโหลดค่าเหล่านี้จากไฟล์ JSON ได้โดยตรง หรือจะเก็บไว้ด้วยวิธีอื่นๆ ที่ปลอดภัยก็ได้ ดูตัวอย่างเมธอด ClientInfo.Load ในโปรเจ็กต์ Google.Apis.Auth.AspNetCore3.IntegrationTests เพื่อดูตัวอย่างการโหลดค่าเหล่านี้จากไฟล์ 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();
    
        ...
    }
          
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        ...
        app.UseHttpsRedirection();
        ...
    
        app.UseAuthentication();
        app.UseAuthorization();
    
        ...
    }
          

ใช้ข้อมูลเข้าสู่ระบบของผู้ใช้เพื่อเข้าถึง Google API ในนามของผู้ใช้

ตอนนี้คุณก็พร้อมที่จะเพิ่มวิธีดําเนินการลงในตัวควบคุมที่กําหนดให้ผู้ใช้ต้องใช้ข้อมูลรับรองในการเข้าถึง Google API ในนามของพวกเขา ข้อมูลโค้ดต่อไปนี้แสดงวิธีแสดงรายการไฟล์ในบัญชี Google ไดรฟ์ของผู้ใช้ที่ตรวจสอบสิทธิ์แล้ว โปรดสังเกต 2 สิ่งต่อไปนี้เป็นส่วนใหญ่

  • ผู้ใช้ต้องได้รับการตรวจสอบสิทธิ์เท่านั้น แต่ยังต้องให้สิทธิ์ขอบเขต https://www.googleapis.com/auth/drive.readonly แก่แอปพลิเคชันอีกด้วยซึ่งคุณระบุผ่านแอตทริบิวต์ GoogleScopedAuthorize
  • เราใช้กลไกการแทรกมาตรฐาน Dependency ของ ASP.NET Core 3&#39 เพื่อรับ 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);
    }
          

สิ่งเหล่านี้คือพื้นฐานเบื้องต้น คุณอาจดูที่ HomeController.cs จากโปรเจ็กต์ Google.Apis.Auth.AspNetCore3.IntegrationTests เพื่อดูว่าจะประสบความสําเร็จได้อย่างไร

  • การตรวจสอบสิทธิ์ผู้ใช้เท่านั้น โดยไม่มีขอบเขตที่เฉพาะเจาะจง
  • ฟังก์ชันการออกจากระบบ
  • การให้สิทธิ์ที่เพิ่มขึ้นผ่านโค้ด โปรดสังเกตว่าข้อมูลโค้ดข้างต้นจะแสดงการให้สิทธิ์ที่เพิ่มขึ้นผ่านแอตทริบิวต์
  • ตรวจสอบขอบเขตที่ได้รับในปัจจุบัน
  • ตรวจสอบการเข้าถึงและรีเฟรชโทเค็น
  • บังคับให้รีเฟรชโทเค็นเพื่อการเข้าถึง คุณไม่จําเป็นต้องดําเนินการนี้ด้วยตนเองเนื่องจาก Google.Apis.Auth.AspNetCore3 จะตรวจหาว่าโทเค็นเพื่อการเข้าถึงหมดอายุหรือใกล้หมดอายุและจะรีเฟรชโดยอัตโนมัติ

เว็บแอปพลิเคชัน (ASP.NET MVC)

Google APIs รองรับ OAuth 2.0 สําหรับแอปพลิเคชันเว็บเซิร์ฟเวอร์ ในการเรียกใช้โค้ดต่อไปนี้ให้เสร็จสมบูรณ์ คุณต้องเพิ่ม URI การเปลี่ยนเส้นทางไปยังโปรเจ็กต์ในคอนโซล Google API ก่อน เนื่องจากคุณจะใช้ FlowMetadata และการตั้งค่าเริ่มต้น ดังนั้นให้ตั้งค่า URI การเปลี่ยนเส้นทางเป็น your_site/AuthCallback/IndexAsync

หากต้องการค้นหา URI การเปลี่ยนเส้นทางสําหรับข้อมูลเข้าสู่ระบบ OAuth 2.0 ให้ทําดังนี้

  1. เปิดหน้าข้อมูลเข้าสู่ระบบในคอนโซล API
  2. หากยังไม่ได้ดําเนินการ ให้สร้างข้อมูลเข้าสู่ระบบ OAuth 2.0 โดยคลิกสร้างข้อมูลเข้าสู่ระบบ > รหัสไคลเอ็นต์ OAuth
  3. หลังจากที่คุณสร้างข้อมูลเข้าสู่ระบบแล้ว ให้ดูหรือแก้ไข URL เปลี่ยนเส้นทางโดยคลิกรหัสไคลเอ็นต์ (สําหรับเว็บแอปพลิเคชัน) ในส่วนรหัสไคลเอ็นต์ OAuth 2.0

หลังจากสร้างโปรเจ็กต์เว็บแอปพลิเคชันใหม่ใน IDE แล้ว ให้เพิ่มแพ็กเกจ Nunu ที่เหมาะสม Google.Apis สําหรับ ไดรฟ์, YouTube หรือบริการอื่นๆ ที่ต้องการใช้ จากนั้นเพิ่มแพ็กเกจ Google.Apis.Auth.MVC โค้ดต่อไปนี้แสดงแอปพลิเคชัน ASP.NET MVC ที่ค้นหาบริการ Google API

  1. เพิ่มการใช้งาน FlowMetadata ของคุณเอง
    using System;
    using System.Web.Mvc;
    
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Auth.OAuth2.Flows;
    using Google.Apis.Auth.OAuth2.Mvc;
    using Google.Apis.Drive.v2;
    using Google.Apis.Util.Store;
    
    namespace Google.Apis.Sample.MVC4
    {
        public class AppFlowMetadata : FlowMetadata
        {
            private static readonly IAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                    {
                        ClientSecrets = new ClientSecrets
                        {
                            ClientId = "PUT_CLIENT_ID_HERE",
                            ClientSecret = "PUT_CLIENT_SECRET_HERE"
                        },
                        Scopes = new[] { DriveService.Scope.Drive },
                        DataStore = new FileDataStore("Drive.Api.Auth.Store")
                    });
    
            public override string GetUserId(Controller controller)
            {
                // In this sample we use the session to store the user identifiers.
                // That's not the best practice, because you should have a logic to identify
                // a user. You might want to use "OpenID Connect".
                // You can read more about the protocol in the following link:
                // https://developers.google.com/accounts/docs/OAuth2Login.
                var user = controller.Session["user"];
                if (user == null)
                {
                    user = Guid.NewGuid();
                    controller.Session["user"] = user;
                }
                return user.ToString();
    
            }
    
            public override IAuthorizationCodeFlow Flow
            {
                get { return flow; }
            }
        }
    }
          

    FlowMetadata เป็นคลาสนามธรรมที่มีตรรกะของคุณเองสําหรับการดึงข้อมูลตัวระบุผู้ใช้และ IAuthorizationCodeFlow ที่คุณใช้อยู่

    ในโค้ดตัวอย่างข้างต้น ระบบจะสร้าง GoogleAuthorizationCodeFlow ใหม่ที่มีขอบเขต รหัสลับไคลเอ็นต์ และที่เก็บข้อมูลที่ถูกต้อง ลองเพิ่มการใช้งาน IDataStore ของคุณเอง เช่น อาจเขียนที่ใช้ EntityFramework

  2. ใช้ตัวควบคุมของคุณเองที่ใช้บริการ Google API ตัวอย่างต่อไปนี้ใช้ DriveService:
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web.Mvc;
    
    using Google.Apis.Auth.OAuth2.Mvc;
    using Google.Apis.Drive.v2;
    using Google.Apis.Services;
    
    using Google.Apis.Sample.MVC4;
    
    namespace Google.Apis.Sample.MVC4.Controllers
    {
        public class HomeController : Controller
        {
            public async Task<ActionResult> IndexAsync(CancellationToken cancellationToken)
            {
                var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
                    AuthorizeAsync(cancellationToken);
    
                if (result.Credential != null)
                {
                    var service = new DriveService(new BaseClientService.Initializer
                        {
                            HttpClientInitializer = result.Credential,
                            ApplicationName = "ASP.NET MVC Sample"
                        });
    
                    // YOUR CODE SHOULD BE HERE..
                    // SAMPLE CODE:
                    var list = await service.Files.List().ExecuteAsync();
                    ViewBag.Message = "FILE COUNT IS: " + list.Items.Count();
                    return View();
                }
                else
                {
                    return new RedirectResult(result.RedirectUri);
                }
            }
        }
    }
          
  3. ใช้ตัวควบคุมการเรียกกลับของคุณเอง การติดตั้งใช้งานควรมีลักษณะดังนี้
    using Google.Apis.Sample.MVC4;
    
    namespace Google.Apis.Sample.MVC4.Controllers
    {
        public class AuthCallbackController : Google.Apis.Auth.OAuth2.Mvc.Controllers.AuthCallbackController
        {
            protected override Google.Apis.Auth.OAuth2.Mvc.FlowMetadata FlowData
            {
                get { return new AppFlowMetadata(); }
            }
        }
    }
          

บัญชีบริการ

Google API ยังรองรับบัญชีบริการอีกด้วย บัญชีบริการนี้มอบสิทธิ์การเข้าถึงข้อมูลของแอปพลิเคชันของตัวเอง ซึ่งต่างจากในสถานการณ์ที่แอปพลิเคชันไคลเอ็นต์ขอสิทธิ์เข้าถึงข้อมูลของผู้ใช้ปลายทาง

แอปพลิเคชันไคลเอ็นต์จะลงนามคําขอโทเค็นเพื่อการเข้าถึงโดยใช้คีย์ส่วนตัวที่ดาวน์โหลดจากคอนโซล Google API หลังจากสร้างรหัสไคลเอ็นต์ใหม่แล้ว คุณควรเลือกประเภทแอปพลิเคชัน "บัญชีบริการ" แล้วดาวน์โหลดคีย์ส่วนตัวได้ อ่านตัวอย่างบัญชีบริการโดยใช้ 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