簡體   English   中英

帶有服務帳戶的Google協調中心OAuth2

[英]Google Coordinate OAuth2 with Service Account

我有一個帶有Google Coordinate .Net庫和“服務帳戶”打開身份驗證的C#控制台應用程序。

private const string SERVICE_ACCOUNT_EMAIL = "XXX@developer.gserviceaccount.com";
private const string SERVICE_ACCOUNT_PKCS12_FILE_PATH = @"<path-to-private-key-file>\YYY-privatekey.p12";
private const string GOOGLE_COORDINATE_TEAM_ID = "ZZZ";

private CoordinateService BuildService()
{
    X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);

    var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate){
        ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
        Scope = CoordinateService.Scopes.Coordinate.GetStringValue()
    };
    var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);

    return new CoordinateService(new BaseClientService.Initializer(){
        Authenticator = auth
    });
}

//some code that retrieves data from coordinate service
public void DoSomething()
{
    CoordinateService service = BuildService();
    var response = service.Jobs.List(GOOGLE_COORDINATE_TEAM_ID).Fetch();
    ...
}

從協調中心服務檢索作業列表時,發生DotNetOpenAuth.Messaging.ProtocolException(內部異常“遠程服務器返回錯誤:(400)錯誤的請求”)。 使用Fiddler,我設法看到了來自Google OAuth服務的響應。 JSON響應對象:

{
  "error" : "invalid_grant"
}

我已經閱讀了一些建議更改本地服務器時間以與Google OAth服務器時間匹配的文章。 但是在將時間更改為另一方后,問題仍然相同。 您能給我一些想法為什么會這樣嗎? 感謝您的所有回復!

服務帳戶不能與Coordinate API一起使用。 [這是因為協調中心API要求經過身份驗證的API用戶具有協調中心許可證,但是無法將協調中心許可證附加到服務帳戶中]

您可以改用網絡服務器流程,請在下面找到示例。

確保更新下面的代碼,其中包含“ TO UPDATE”的注釋。

using System; 
using System.Diagnostics; 
using System.Collections.Generic; 
using DotNetOpenAuth.OAuth2; 
using Google.Apis.Authentication.OAuth2; 
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; 
using Google.Apis.Coordinate.v1; 
using Google.Apis.Coordinate.v1.Data;

namespace Google.Apis.Samples.CoordinateOAuth2
{ 
    /// <summary> 
    /// This sample demonstrates the simplest use case for an OAuth2 service. 
    /// The schema provided here can be applied to every request requiring authentication. 
    /// </summary> 
    public class ProgramWebServer
    { 
        public static void Main (string[] args)
        { 
            // TO UPDATE, can be found in the Coordinate application URL
            String TEAM_ID = "jskdQ--xKjFiFqLO-IpIlg"; 

            // Register the authenticator. 
            var provider = new WebServerClient (GoogleAuthenticationServer.Description);
            // TO UPDATE, can be found in the APIs Console.
            provider.ClientIdentifier = "335858260352.apps.googleusercontent.com";
            // TO UPDATE, can be found in the APIs Console.
            provider.ClientSecret = "yAMx-sR[truncated]fX9ghtPRI"; 
            var auth = new OAuth2Authenticator<WebServerClient> (provider, GetAuthorization); 

            // Create the service. 
            var service = new CoordinateService(new BaseClientService.Initializer()
                       {
                          Authenticator = auth
                       });

            //Create a Job Resource for optional parameters https://developers.google.com/coordinate/v1/jobs#resource 
            Job jobBody = new Job (); 
            jobBody.Kind = "Coordinate#job"; 
            jobBody.State = new JobState (); 
            jobBody.State.Kind = "coordinate#jobState"; 
            jobBody.State.Assignee = "user@example.com"; 


            //Create the Job 
            JobsResource.InsertRequest ins = service.Jobs.Insert (jobBody, TEAM_ID, "My Home", "51", "0", "Created this Job with the .Net Client Library");
            Job results = ins.Fetch (); 

            //Display the response 
            Console.WriteLine ("Job ID:"); 
            Console.WriteLine (results.Id.ToString ()); 
            Console.WriteLine ("Press any Key to Continue"); 
            Console.ReadKey (); 
        }

        private static IAuthorizationState GetAuthorization (WebServerClient client)
        { 
            IAuthorizationState state = new AuthorizationState (new[] { "https://www.googleapis.com/auth/coordinate" }); 
            // The refresh token has already been retrieved offline
            // In a real-world application, this has to be stored securely, since this token
            // gives access to all user data on the Coordinate scope, for the user who accepted the OAuth2 flow
            // TO UPDATE (see below the sample for instructions)
            state.RefreshToken = "1/0KuRg-fh9yO[truncated]yNVQcXcVYlfXg";

            return state;
        } 

    } 
}

可以使用OAuth2游樂場檢索刷新令牌:

  • 在API控制台中,添加OAuth Playground URL https://developers.google.com/oauthplayground作為授權的重定向URI(在下面的OAuth Playground中檢索刷新令牌時,我們將需要它)
  • 在已驗證您的API用戶身份的瀏覽器會話中,轉到OAuth游樂場(該用戶需要擁有Coordinate許可證)。 確保提供您自己的OAuth2客戶端ID(“設置”>“使用您自己的OAuth憑據”) 否則,您的刷新令牌將與OAuth2游樂場的內部OAuth2客戶端ID綁定在一起,當您要將刷新令牌與自己的客戶端ID一起使用以獲取訪問令牌時,刷新令牌將被拒絕。
  • 使用范圍https://www.googleapis.com/auth/coordinate在步驟1中,點擊“授權API”在步驟2中,點擊“令牌的Exchange授權代碼”
  • 在代碼中復制刷新令牌。 保持安全。
  • 此刷新令牌不會過期,因此您的應用將保持身份驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM