如何实施OAUTH 2.0以访问Google Analytics [英] How to implement OAUTH 2.0 to access Google Analytics

查看:121
本文介绍了如何实施OAUTH 2.0以访问Google Analytics的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读Google停止使用以前的身份验证方法来访问Google API,因此我们现在必须使用该OAuth2身份验证方法。我读过,我们必须去开发人员控制台并获取ClientID和客户端密钥,以便我们可以执行身份验证。但是我遇到了很大的麻烦,需要对必要的更改进行编码以便成功登录。



我正在搜索指南,以便在登录级别执行更改。我尝试应用我在网上找到的一些代码,但我没有成功。关于开发者控制台我已经有了一个带有ClientID和Secret的项目,所以我没有生成一个新的项目,但是使用了已经生成的ClientID和Secret。



这是Google改变之前的工作代码:

  {
///< summary>
/// GoogleAnalytics
的摘要说明///< / summary>
[WebService(Namespace =http://tempuri.org/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class GoogleAnalytics:System.Web.Services.WebService
{
[WebMethod]
public string GetAnalyticsPageViews()
{
string returnValue = string.Empty;

对象cacheObjPageViewsCount = CacheService.Get(CacheService.ANALYTICSPAGEVIEWS);

if(cacheObjPageViewsCount!= null)
returnValue = cacheObjPageViewsCount as string;
else
{
try
{
string userName = Configurations.GetConfigurationValueAsString(GoogleAnalyticsUsername);
string passWord = Configurations.GetConfigurationValueAsString(GoogleAnalyticsPassword);
string profileId = Configurations.GetConfigurationValueAsString(GoogleAnalyticsProfileId);

const string dataFeedUrl =https://www.googleapis.com/analytics/v2.4/data;

AnalyticsService服务=新AnalyticsService(ApplicationName);
if(!string.IsNullOrEmpty(userName))
{
service.setUserCredentials(userName,passWord);
}

DataQuery query1 = new DataQuery(dataFeedUrl);
query1.Ids​​ =ga:+ profileId;
query1.Metrics =ga:visits;
query1.Sort =ga:visits;
query1.GAStartDate = DateTime.Now.AddYears(-1).ToString(yyyy-MM-dd);
query1.GAEndDate = DateTime.Now.ToString(yyyy-MM-dd);
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);
DataEntry dataEntry =(DataEntry)dataFeedVisits.Entries [0];
returnValue = dataEntry.Metrics [0] .Value;
}
catch(Exception exc)
{
LogService.LogException(exc);
returnValue = string.Empty;
}

CacheService.Add(CacheService.PP_ANALYTICSPAGEVIEWS_COUNT_CACHE_KEY,returnValue);
}

return returnValue;
}
}
}

这是我尝试执行的更改



而不是使用ifservice.setUserCredentials(userName,passWord);
我使用GoogleOAutho2.authenticate();
这样做的结果是,它打开了一个新页面,出现此错误:请求中的重定向URI: http: // localhost:60279 / authorize / 与注册的重定向URI不匹配。



我不明白为什么我发送到新页面,这没有发生以前的身份验证方法,我在哪里丢失?



在此先感谢,
N



我发送到的网页:

https://accounts.google.com/o/oauth2/auth?access_type=offline&response_type=code&client_id= clientid & amp ; redirect_uri = http:// localhost:60279 / authorize /& scope = https://www.googleapis.com/auth/analytics%20https://www.googleapis.com/ auth / analytics.edit%20https://www.googleapis.com/auth/analytics.manage.users%20https://www.googleapis.com/auth/analytics.readonly



(此代码基于此示例

  using System; 
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用Google.Apis.Analytics.v3;
使用Google.Apis.Auth.OAuth2;
使用System.Threading;
使用Google.Apis.Util.Store;
使用Google.Apis.Services;
使用System.Security.Cryptography.X509Certificates;
使用System.IO;

namespace GoogleOAuth2 {
$ b $ class GoogleOAutho2
{

static string [] scopes = new string [] {
AnalyticsService .Scope.Analytics,//查看和管理您的Google Analytics数据
AnalyticsService.Scope.AnalyticsEdit,//编辑和管理Google Analytics帐户
AnalyticsService.Scope.AnalyticsManageUsers,//编辑和管理Google Analytics用户
AnalyticsService.Scope.AnalyticsReadonly}; //查看Google Analytics数据

static String CLIENT_ID =CLIENTID; //在开发人员控制台中找到
static String CLIENT_SECRET =SECRET; //在开发人员控制台中找到
//这里是我们要求用户给我们访问的地方,或者使用先前的刷新令牌存储在%AppData%


public static bool authenticate()
{

try
{
UserCredential credential = GoogleWebAuthorizationBroker .AuthorizeAsync(新的ClientSecrets {ClientId = CLIENT_ID,ClientSecret = CLIENT_SECRET},作用域,Environment.UserName,CancellationToken.None,新的FileDataStore(XXX.GoogleAnalytics.Auth.Store))。

返回true;
}
catch(Exception exeption)
{
string error = exeption.Message;
返回false;
}
}
}
}


解决方案

不知道这是否有帮助。我没有使用这些相同的类,甚至没有使用C#。我使用的方法是直接http调用。在我的实施中,我致电 https://accounts.google.com/o/oauth2/ auth 作为 redirect_uri 参数传递给API contsole中指定的相同值(请参阅屏幕快照)。



这是通过/指定的任何地方?


I've Read that Google discontinued the previous authentication method to access Google API, so now we have to use that OAuth2 Authentication method. I've read that we have to go to the Developer console and get the ClientID and Client Secret so that we can perform the authentication. But I'm having big troubles to code the necessary changes to successfully Login.

I'm Searching for guidelines to do the changes at the login level. I tried to apply some code I found on the web, but I wasn't successful. About the Developer Console I already have a Project with the ClientID and Secret so I didn't generated a new one but used the ClientID and Secret already generated.

This is the working code, before google change:

    {
    /// <summary>
    /// Summary description for GoogleAnalytics
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class GoogleAnalytics : System.Web.Services.WebService
    {
        [WebMethod]
        public string GetAnalyticsPageViews()
        {
            string returnValue = string.Empty;

            object cacheObjPageViewsCount = CacheService.Get(CacheService.ANALYTICSPAGEVIEWS);

            if (cacheObjPageViewsCount != null)
                returnValue = cacheObjPageViewsCount as string;
            else
            {
                try
                {
                    string userName = Configurations.GetConfigurationValueAsString("GoogleAnalyticsUsername");
                    string passWord = Configurations.GetConfigurationValueAsString("GoogleAnalyticsPassword");
                    string profileId = Configurations.GetConfigurationValueAsString("GoogleAnalyticsProfileId");

                    const string dataFeedUrl = "https://www.googleapis.com/analytics/v2.4/data";

                    AnalyticsService service = new AnalyticsService("ApplicationName");
                    if (!string.IsNullOrEmpty(userName))
                    {
                        service.setUserCredentials(userName, passWord);
                    }

                    DataQuery query1 = new DataQuery(dataFeedUrl);
                    query1.Ids = "ga:" + profileId;
                    query1.Metrics = "ga:visits";
                    query1.Sort = "ga:visits";
                    query1.GAStartDate = DateTime.Now.AddYears(-1).ToString("yyyy-MM-dd");
                    query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
                    query1.StartIndex = 1;
                    DataFeed dataFeedVisits = service.Query(query1);
                    DataEntry dataEntry = (DataEntry)dataFeedVisits.Entries[0];
                    returnValue = dataEntry.Metrics[0].Value;
                }
                catch (Exception exc)
                {
                    LogService.LogException(exc);
                    returnValue = string.Empty;
                }

                CacheService.Add(CacheService.PP_ANALYTICSPAGEVIEWS_COUNT_CACHE_KEY, returnValue);
            }

            return returnValue;
        }
    }
}

This is the changes that I tried to perform

Instead of using if "service.setUserCredentials(userName, passWord);" I use "GoogleOAutho2.authenticate();" the result of this is that it's open a new page with this error: The redirect URI in the request: http://localhost:60279/authorize/ did not match a registered redirect URI.

I didnt understand why im send to a new page, this didnt happen with the previous authentication method, Where am I missing?

Thanks in Advance, N

The page that I'm sended to:

https://accounts.google.com/o/oauth2/auth?access_type=offline&response_type=code&client_id=clientid&redirect_uri=http://localhost:60279/authorize/&scope=https://www.googleapis.com/auth/analytics%20https://www.googleapis.com/auth/analytics.edit%20https://www.googleapis.com/auth/analytics.manage.users%20https://www.googleapis.com/auth/analytics.readonly

(this code is base on this samples)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.Apis.Analytics.v3;
using Google.Apis.Auth.OAuth2;
using System.Threading;
using Google.Apis.Util.Store;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace GoogleOAuth2 { 

class GoogleOAutho2
{

    static string[] scopes = new string[] {
        AnalyticsService.Scope.Analytics,  // view and manage your Google Analytics data
        AnalyticsService.Scope.AnalyticsEdit,  // Edit and manage Google Analytics Account
        AnalyticsService.Scope.AnalyticsManageUsers,   // Edit and manage Google Analytics Users
        AnalyticsService.Scope.AnalyticsReadonly};     // View Google Analytics Data

    static String CLIENT_ID = "CLIENTID"; // found in Developer console
    static String CLIENT_SECRET = "SECRET";// found in Developer console
    // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%


    public static bool authenticate()
    {

        try
        {
            UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = CLIENT_ID, ClientSecret = CLIENT_SECRET }, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("XXX.GoogleAnalytics.Auth.Store")).Result;

            return true;
        }
        catch (Exception exeption)
        {
            string error = exeption.Message;
            return false;
        }
    }
}
}

解决方案

Not sure if this will help. I am not using these same classes, and not even C#. The approach I use is straight http calls. In my implementation I call https://accounts.google.com/o/oauth2/auth passing as the redirect_uri parameter the same value specified in the API contsole (see screen shot).

Is this being passed/specified anywhere?

这篇关于如何实施OAUTH 2.0以访问Google Analytics的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆