在C#中使用AccessType = Offline的Google Analytics OAuth

时间:2014-02-28 11:59:30

标签: c# google-api-dotnet-client

我想使用OAuth使用Google AnalyticsAPI。

我正在使用这个库: http://code.google.com/p/google-api-dotnet-client/

以下代码用于身份验证:

var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
    new ClientSecrets { ClientId = "...", ClientSecret = "..." },
    new[] {Google.Apis.Analytics.v3.AnalyticsService.Scope.AnalyticsReadonly},
    "user",
    CancellationToken.None,
    new FileDataStore("Analytics.Auth.Store")).Result;

var service = new Google.Apis.Analytics.v3.AnalyticsService(
    new BaseClientService.Initializer
    {
        HttpClientInitializer = credential,
        ApplicationName = "...",
    });

我可以将它与refresh_token一起使用,这样我就不必每隔几天接受一次授权请求吗?

在这个问题的答案中: Service Account Google Analytics OAuth AccessType = Offline C#

2 个答案:

答案 0 :(得分:12)

我只知道一种方式:您需要覆盖GoogleAuthorizationCodeRequestUrl,但我不知道如何将其与AuthorizationBroker一起使用。

internal class ForceOfflineGoogleAuthorizationCodeFlow : GoogleAuthorizationCodeFlow
{
    public ForceOfflineGoogleAuthorizationCodeFlow(AuthorizationCodeFlow.Initializer initializer) : base(initializer) { }

    public override AuthorizationCodeRequestUrl CreateAuthorizationCodeRequest(string redirectUri)
    {
        return new GoogleAuthorizationCodeRequestUrl(new Uri(AuthorizationServerUrl))
                {
                    ClientId = ClientSecrets.ClientId,
                    Scope = string.Join(" ", Scopes),
                    RedirectUri = redirectUri,
                    AccessType = "offline",
                    ApprovalPrompt = "force"
                };
    }
};

看起来他们在经纪人中创建了Flow: GoogleWebAuthorizationBroker.cs

我没有看到任何通过params或替换AuthorizationCodeFlow

的方法

答案 1 :(得分:7)

显然我不能发表评论,但要延伸Darida的回答:

制作自定义CodeFlow

public class CustomAuthorizationCodeFlow : GoogleAuthorizationCodeFlow
{
    public CustomAuthorizationCodeFlow(GoogleAuthorizationCodeFlow.Initializer initializer) : base(initializer) { }

    public override AuthorizationCodeRequestUrl CreateAuthorizationCodeRequest(String redirectUri)
    {
        return new GoogleAuthorizationCodeRequestUrl(new Uri(AuthorizationServerUrl))
        {
            ClientId = ClientSecrets.ClientId,
            Scope = string.Join(" ", Scopes),
            RedirectUri = redirectUri,
            AccessType = "online",
            ApprovalPrompt = "auto"
        };
    }
}

然后制作自定义FlowMetadata

public class AppFlowMetadata : FlowMetadata
{
    private static readonly IAuthorizationCodeFlow flow =
        new CustomAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets
            {
                ClientId = "...",
                ClientSecret = "..."
            },
            Scopes = new String[] { AnalyticsService.Scope.AnalyticsReadonly },
            DataStore = new EFDataStore(),
        });

    public override IAuthorizationCodeFlow Flow
    {
        get { return flow; }
    }

    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.

        return String.Format("user-{0}", WebSecurity.GetUserId(controller.User.Identity.Name));
    }
}

然后在Controller

public ActionResult Sample()
{
    var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);

    if (result.Credential != null)
    {
        var service = new AnalyticsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = result.Credential,
            ApplicationName = APPLICATION_NAME
        });
   }
}