Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 通过OAuth 2.0自动使用google api dotnet客户端_.net_Vb.net_Google Analytics Api_Google Api Client - Fatal编程技术网

.net 通过OAuth 2.0自动使用google api dotnet客户端

.net 通过OAuth 2.0自动使用google api dotnet客户端,.net,vb.net,google-analytics-api,google-api-client,.net,Vb.net,Google Analytics Api,Google Api Client,我有一组密钥:客户机id、客户机机密、api密钥 但所有文档都显示了使用人机交互的身份验证 在没有用户交互的情况下,如何使用dot net库与Google API v3和AnalyticsService交互?如果我只使用API键,我会得到“Google.API.Requests.RequestError Login Required” 我在任何地方都找不到这样的样品 编辑:这是一个Google Analytics帐户,我可以完全访问它,用户名,密码,客户id,客户机密,api/开发者密钥,一切。

我有一组密钥:客户机id、客户机机密、api密钥

但所有文档都显示了使用人机交互的身份验证

在没有用户交互的情况下,如何使用dot net库与Google API v3和AnalyticsService交互?如果我只使用API键,我会得到“Google.API.Requests.RequestError Login Required”

我在任何地方都找不到这样的样品


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

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

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

也张贴在这里

命令行调用示例: C:\DW\googleanalyticsnices\googleanalyticsnices.exe“ga:XXXX9049”“2012-04-01”“2012-04-01”“ga:visitors,ga:newvisions,ga:visitors,ga:bounces,ga:pageviews”“ga:date,ga:medium”“xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-privatekey.p12”“XXXXX.@developer.gserviceaccount.com”“RegKey”>C:\Data\NicheSites\ga\u 58589049\u moneyjobs.com\u 20120401.txt

使用系统;
使用System.Collections.Generic;
使用System.Net.Http;
使用System.Security.Cryptography;
使用System.Security.Cryptography.X509证书;
使用系统文本;
使用DotNetOpenAuth.OAuth2;
使用Google.api.Analytics.v3;
使用Google.api.Analytics.v3.Data;
使用Google.api.Authentication.OAuth2.DotNetOpenAuth;
使用Microsoft.Win32;
使用Newtonsoft.Json;
命名空间控制台应用程序5
{
班级计划
{
公共静态字符串访问_token=“”;
公共静态字符串expire\u time=string.Empty;
公共静态字符串profileId=string.Empty;
公共静态字符串度量=string.Empty;
公共静态字符串维度=string.Empty;
公共静态字符串startDate=string.Empty;
公共静态字符串endDate=string.Empty;
公共静态字符串privatekeyFile=string.Empty;
公共静态字符串loginEmail=string.Empty;
公共静态字符串regKeyName=string.Empty;
静态void Main(字符串[]参数)
{
profileId=args[0];
startDate=args[1];
endDate=args[2];
指标=参数[3];
尺寸=args[4];
privatekeyFile=args[5];
loginEmail=args[6];
regKeyName=args[7];
尝试
{
//证书
字符串路径=System.Reflection.Assembly.GetExecutionGassembly().CodeBase;
var directory=System.IO.Path.GetDirectoryName(Path).Remove(0,6);
var certificate=new X509Certificate2(目录+“\\”+私有密钥文件,“notasecret”);
尝试
{
expire_time=(string)Registry.LocalMachine.OpenSubKey(@“SOFTWARE\Wow6432Node\CB\”+regKeyName).GetValue(“ExpireTime”).ToString();
}
捕获(例外e)
{
注册表键;
key=Registry.LocalMachine.CreateSubKey(@“SOFTWARE\CB\”+regKeyName);
key.SetValue(“OAuthToken”,即“”);
key.Close();
}
尝试
{
access_token=(string)Registry.LocalMachine.OpenSubKey(@“SOFTWARE\Wow6432Node\CB\”+regKeyName).GetValue(“OAuthToken”).ToString();
}
捕获(例外e)
{
注册表键;
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)
{
过期时间=“01/01/2000”;
}
var ExpireDateTime=Convert.ToDateTime(expire\u time);
var ExpireTimeNow=DateTime.UtcNow;
TimeSpan=ExpiredAtTime-ExpiretItemNow;
double iExpireLeft=span.TotalSeconds;
如果(iExpireLeft<60)
{
//标题
var header=new{typ=“JWT”,alg=“RS256”};
//索赔集
var times=GetExpiryAndIssueDate();
var claimset=new
{
iss=loginEmail,
范围=”https://www.googleapis.com/auth/analytics.readonly",
澳元=”https://accounts.google.com/o/oauth2/token",
iat=次[0],
exp=次[1],
};
//编码头
var headerSerialized=JsonConvert.Serialized对象(标头);
var headerBytes=Encoding.UTF8.GetBytes(headerSerialized);
var headerEncoded=Base64UrlEncode(headerBytes);
//编码索赔集
var claimsetSerialized=JsonConvert.serialized对象(claimset);
var claimsetBytes=Encoding.UTF8.GetBytes(claimsetSerialized);
var claimsetEncoded=Base64UrlEncode(claimsetBytes);
//输入
var输入=headerEncoded+“”+claimsetEncoded;
var inputBytes=Encoding.UTF8.GetByte
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; 
        //}

    }
}