通过 OAuth 2.0 自动使用 google-api-dotnet-client

Posted

技术标签:

【中文标题】通过 OAuth 2.0 自动使用 google-api-dotnet-client【英文标题】:Automated use of google-api-dotnet-client with OAuth 2.0 【发布时间】:2012-09-07 21:45:07 【问题描述】:

我有一堆密钥:客户端 ID、客户端密码、API 密钥

但所有文档都显示使用人工交互进行身份验证。

如何使用点网库与 Google API v3 和 AnalyticsService 进行交互而无需用户交互?如果我只使用 API 密钥,我会得到“需要 Google.Apis.Requests.RequestError 登录”

我在任何地方都找不到这样做的样本。

编辑:这是一个 Google Analytics 帐户,我可以完全访问它、用户名、密码、客户端 ID、客户端密码、api/开发人员密钥,一切。我只想让实用程序每天在没有我的情况下下载数据。

【问题讨论】:

要以用户身份进行身份验证,您仍然需要人类的登录信息和密码,因此需要人类交互。我相信一旦用户授权了您的应用程序,它就不再需要交互了,但我对 google api 并不完全熟悉。 我有用户名和密码。如果我每次都必须手动授权访问,我该如何创建一个实用程序来自动下载报告? 【参考方案1】:

这是我的工作代码,这是我通过批处理文件进程调用的控制台应用程序。 我不是 .Net 开发人员,所以这段代码可能并不完美,如果您看到任何需要改进的地方,请告诉我! 错误处理很少,因为我不希望一次失败杀死批次

我正在使用注册表来存储访问令牌和过期时间 在应用程序文件夹中还有 privatekey.p12 文件 该帐户是个人资料上的用户而不是管理员。

也在这里发布https://groups.google.com/forum/?fromgroups=#!topic/google-analytics-data-export-api/quIN0vX-psw

命令行调用示例: C:\DW\GoogleAnalyticsNicheSites\GoogleAnalyticsNicheSites.exe "ga:XXXX9049" "2012-04-01" "2012-04-01" "ga:visitors,ga:newVisits,ga:visits,ga:bounces,ga:pageviews" "ga:date,ga:medium" "XXXXXXXXXXXXXXXXXXXXXXXXXXXX-privatekey.p12" "XXXXX...@developer.gserviceaccount.com" "RegKey" > C:\Data\NicheSites\ga_58589049_moneyjobs.com_20120401.txt"

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Microsoft.Win32;
using Newtonsoft.Json;


namespace ConsoleApplication5

    class Program
    
        public static string access_token = "";
        public static string expire_time = string.Empty;
        public static string profileId = string.Empty;
        public static string metrics = string.Empty;
        public static string dimensions = string.Empty;
        public static string startDate = string.Empty;
        public static string endDate = string.Empty;
        public static string privatekeyFile = string.Empty;
        public static string loginEmail = string.Empty;
        public static string regKeyName = string.Empty;

        static void Main(string[] args)
        

            profileId = args[0];
            startDate = args[1];
            endDate = args[2];
            metrics = args[3];
            dimensions = args[4];
            privatekeyFile = args[5];
            loginEmail = args[6];
            regKeyName = args[7];

            try
            
                // certificate
                string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
                var directory = System.IO.Path.GetDirectoryName(path).Remove(0, 6);
                var certificate = new X509Certificate2(directory + "\\" + privatekeyFile , "notasecret");

                try
                
                    expire_time = (string)Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\CB\" + regKeyName).GetValue("ExpireTime").ToString();
                
                catch (Exception e)
                
                    RegistryKey key;
                    key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CB\" + regKeyName);
                    key.SetValue("OAuthToken", "");
                    key.Close();
                

                try
                
                    access_token = (string)Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\CB\" + regKeyName).GetValue("OAuthToken").ToString();
                
                catch (Exception e)
                
                    RegistryKey key;
                    key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CB\" + regKeyName);
                    key.SetValue("ExpireTime", DateTime.UtcNow.AddSeconds(3500).ToString("MM/dd/yyyy HH:mm:ss"));
                    key.Close();
                

                if (expire_time == null || expire_time.Length < 4)
                
                    expire_time = "01/01/2000";
                

                var ExpireDateTime = Convert.ToDateTime(expire_time);
                var ExpireTimeNow = DateTime.UtcNow;
                TimeSpan span = ExpireDateTime - ExpireTimeNow;
                double iExpireLeft = span.TotalSeconds;

                if (iExpireLeft < 60)
                

                    // header
                    var header = new  typ = "JWT", alg = "RS256" ;

                    // claimset
                    var times = GetExpiryAndIssueDate();
                    var claimset = new
                    
                        iss = loginEmail,
                        scope = "https://www.googleapis.com/auth/analytics.readonly",
                        aud = "https://accounts.google.com/o/oauth2/token",
                        iat = times[0],
                        exp = times[1],
                    ;

                    // encoded header
                    var headerSerialized = JsonConvert.SerializeObject(header);
                    var headerBytes = Encoding.UTF8.GetBytes(headerSerialized);
                    var headerEncoded = Base64UrlEncode(headerBytes);

                    // encoded claimset
                    var claimsetSerialized = JsonConvert.SerializeObject(claimset);
                    var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized);
                    var claimsetEncoded = Base64UrlEncode(claimsetBytes);

                    // input
                    var input = headerEncoded + "." + claimsetEncoded;
                    var inputBytes = Encoding.UTF8.GetBytes(input);

                    // signiture
                    var rsa = certificate.PrivateKey as RSACryptoServiceProvider;
                    var cspParam = new CspParameters
                    
                        KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName,
                        KeyNumber = rsa.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2
                    ;
                    var aescsp = new RSACryptoServiceProvider(cspParam)  PersistKeyInCsp = false ;
                    var signatureBytes = aescsp.SignData(inputBytes, "SHA256");
                    var signatureEncoded = Base64UrlEncode(signatureBytes);

                    // jwt
                    var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded;

                    var client = new HttpClient();
                    var uri = "https://accounts.google.com/o/oauth2/token";
                    var post = new Dictionary<string, string>
                
                    "assertion", jwt,
                    "grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"
                ;
                    var content = new FormUrlEncodedContent(post);
                    var result = client.PostAsync(uri, content).Result;

                    RootObject values = JsonConvert.DeserializeObject<RootObject>(result.Content.ReadAsStringAsync().Result);
                    access_token = values.access_token;

                    RegistryKey key;
                    key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CB\" + regKeyName);
                    key.SetValue("OAuthToken", access_token);
                    key.Close();

                    key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CB\" + regKeyName);
                    key.SetValue("ExpireTime", DateTime.UtcNow.AddSeconds(3500).ToString("MM/dd/yyyy HH:mm:ss"));
                    key.Close();
                


                // Create the service.
                var service = new AnalyticsService();
                ListAnalytics(service);
            
            catch (Exception e)
            
                Console.WriteLine(profileId + ": " + e.Message + " " + e.Source + " " + e.StackTrace);
            
        

        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        
            IAuthorizationState state = new AuthorizationState(new[]  "https://www.googleapis.com/auth/analytics.readonly" );
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            state.AccessToken = access_token;
            string authCode = access_token;
            arg.RefreshToken(state); 
            return state;
        

        private static void ListAnalytics(AnalyticsService service)
        
            try
            
                var iCount = 1;
                var iStartIndex = 1;

                while (iCount > 0 )
                
                    var response = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
                    response.Dimensions = dimensions;
                    response.MaxResults = 10000;
                    response.StartIndex = iStartIndex;
                    response.Oauth_token = access_token;
                    GaData report = response.Fetch();

                    Console.Write("ids|");

                    for (int i = 0; i <= report.ColumnHeaders.Count - 2; i++)
                    
                        Console.Write(report.ColumnHeaders[i].Name.ToString() + "|");
                    

                    Console.WriteLine(report.ColumnHeaders[report.ColumnHeaders.Count - 1].Name.ToString());

                    if (null != report.Rows.Count)
                    
                        for (int i = 0; i < report.Rows.Count; i++)
                        

                            IList<string> row = report.Rows[i];
                            Console.Write(profileId + "|");

                            for (int x = 0; x <= row.Count - 2; x++)
                            
                                Console.Write(row[x].ToString() + "|");
                            
                            Console.WriteLine(row[row.Count - 1].ToString());
                        
                        //Console.ReadLine();
                        iCount = report.Rows.Count < 10000 ? 0 : 1;
                    
                    else 
                     
                        iCount = 0;
                    
                    iStartIndex += 10000;
                
            
            catch (Exception ex)
            

            
        

                                    private static int[] GetExpiryAndIssueDate()
    
        var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        var issueTime = DateTime.UtcNow;

        var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
        var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds;

        return new[]  iat, exp ;
    

                                    private static string Base64UrlEncode(byte[] input)
    
        var output = Convert.ToBase64String(input);
        output = output.Split('=')[0]; // Remove any trailing '='s
        output = output.Replace('+', '-'); // 62nd char of encoding
        output = output.Replace('/', '_'); // 63rd char of encoding
        return output;
    

                            public class RootObject
    
        public string access_token  get; set; 
        public string token_type  get; set; 
        public int expires_in  get; set; 
    

        //public static Google.Apis.Authentication.IAuthenticator UseSavedAuthorization()
        //

        //    var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
        //    provider.ClientIdentifier = "XXXXXXXXXXXXXXXXX-6ogef1100hmt92k8frqaprhfr38b4oaq.apps.googleusercontent.com";
        //    provider.ClientSecret = "XXXXXXXXXXXXXXXXXXXXXX";

        //    AuthenticatorFactory.GetInstance().RegisterAuthenticator(() => new OAuth2Authenticator(provider, GetAuthentication));

        //    OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, getState);

        //    auth.LoadAccessToken();

        //    return auth;
        //

        //public static IAuthorizationState getState(NativeApplicationClient arg)
        //
        //    IAuthorizationState state = new AuthorizationState(new[]  AnalyticsService.Scopes.AnalyticsReadonly.ToString() );
        //    state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);

        //    state.RefreshToken = access_token;        
        //    arg.RefreshToken(state); 

        //    return state; 
        //

    

【讨论】:

请注意,服务帐户用于服务器间通信,用于桌面应用程序,因为您将 private 密钥文件暴露给该机器上的任何用户/应用程序!

以上是关于通过 OAuth 2.0 自动使用 google-api-dotnet-client的主要内容,如果未能解决你的问题,请参考以下文章

通过 OAuth 2.0 和私钥(即服务帐户)访问 Google Contacts Api

使用服务帐户通过 OAuth 2.0 调用 v3 Google 日历 API 时出现“需要登录”401 未经授权的消息

需要Google OAuth 2.0架构建议通过Java邮件Api发送Smtp邮件

Google OAuth 2.0 服务帐户 - 日历 API(PHP 客户端)

具有公共访问权限的 Web 应用程序的 Google OAuth 2.0 刷新令牌

Google Gmail API OAuth 2.0 错误 400:redirect_uri_mismatch