繁体   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