谷歌协调OAuth2与服务帐户帐户

由网友(梧叶飘黄)分享简介:我有一个C#控制台应用程序谷歌协调NET库和服务帐户开放式身份验证。I have a C# console application with Google Coordinate .Net library and Service Account open authentication.private const st...

我有一个C#控制台应用程序谷歌协调NET库和服务帐户开放式身份验证。

I have a C# console application with Google Coordinate .Net library and Service Account open authentication.

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)错误的请求)。使用提琴手我设法看到谷歌OAuth的服务响应。 JSON响应对象:

On retrieving list of jobs from Coordinate Service there is DotNetOpenAuth.Messaging.ProtocolException occured (inner exception "The remote server returned an error: (400) Bad Request"). Using Fiddler I managed to see response from Google OAuth service. JSON response object:

{
  "error" : "invalid_grant"
}

我看过一些文章,建议修改本地服务器时间,以配合谷歌的誓言服务器时间。但是改变时间的一个和另一侧之后问题仍然是相同的。 您能给我一些想法,为什么发生这种情况? 感谢所有答复!

I have read some articles that suggest to change local server time in order to match with Google OAth server time. But after changing time to one and other side the problem remains the same. Could you please give me some ideas why this is happening? Thanks for all responses!

推荐答案

服务帐户无法与协调API使用。 [这是因为协调API需要验证的API用户有一个坐标许可,但它不可能附加一个坐标许可给服务帐户]

Service accounts cannot be used with the Coordinate API. [this is because the Coordinate API requires authenticated API users to have a Coordinate license, but it is not possible to attach a Coordinate license to a service account]

您可以使用Web服务器的流量,而不是,请看下面的示例。

You can use the web server flow instead, please find the sample below.

请确保更新code以下,其中有含更新的意见。

Make sure to update the code below, where there are comments containing "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游乐场检索:

A refresh token can be retrieved by using the OAuth2 Playground:

在API控制台,添加OAuth园地网址, https://developers.google.com/oauthplayground,作为授权的 重定向URI(我们需要当我们检索刷新令牌在 OAuth的游乐场,下同) 转到OAuth的游乐场,在一个浏览器会话,有你的API的用户身份验证(该用户需要有一个协调的许可)。 确保提供 你自己OAuth2客户端ID(设置>使用您自己的OAuth凭证)。 否则,你刷新令牌将被捆绑到OAuth2操场的 内部OAuth2客户端ID,并会在你需要使用被拒绝 与自己的客户端ID刷新令牌来获得访问令牌。 使用范围 https://www.googleapis.com/auth/coordinate 在步骤1, 点击授权的API在第2步,点击兑换授权codeS 令牌 复制刷新令牌在code。保证它的安全。 在此刷新令牌不会过期,所以您的应用程序将保持认证。 In the APIs Console, add the OAuth Playground URL, https://developers.google.com/oauthplayground, as an authorized redirect URI (we’ll need that when we retrieve a refresh token in the OAuth Playground, below) Go to the OAuth Playground, in a browser session that has your API user authenticated (this user needs to have a Coordinate license). Make sure to provide you own OAuth2 client ID (Settings > Use your own OAuth credentials). Otherwise, your refresh token will be tied to the OAuth2 playground's internal OAuth2 client ID, and will be rejected when you want to use the refresh token with your own client IDs to get an access token. Use the scope https://www.googleapis.com/auth/coordinate In Step 1, hit "Authorize the API" In Step 2, hit "Exchange Authorization codes for tokens" Copy the refresh token in your code. Keep it secure. This refresh token does not expire, so your app will stay authenticated.
阅读全文

相关推荐

最新文章