【问题标题】:How to implement OAUTH 2.0 to access Google Analytics如何实施 OAUTH 2.0 以访问 Google Analytics
【发布时间】:2015-10-02 22:36:29
【问题描述】:

我读到 Google 停止使用之前的身份验证方法来访问 Google API,所以现在我们必须使用该 OAuth2 身份验证方法。我读到我们必须去开发者控制台并获取 ClientID 和 Client Secret 以便我们可以执行身份验证。但是我在编写必要的更改以成功登录时遇到了很大的麻烦。

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

这是谷歌更改之前的工作代码:

    {
    /// <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;
        }
    }
}

这是我尝试执行的更改

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

我不明白为什么我要发送到新页面,以前的身份验证方法不会发生这种情况,我错过了哪里?

提前致谢, 否

我被发送到的页面:

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 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;
        }
    }
}
}

【问题讨论】:

    标签: c# google-analytics oauth-2.0


    【解决方案1】:

    不确定这是否会有所帮助。我没有使用这些相同的类,甚至没有使用 C#。我使用的方法是直接的 http 调用。在我的实现中,我调用 https://accounts.google.com/o/oauth2/auth 作为 redirect_uri 参数传递 API 控制台中指定的相同值(参见屏幕截图)。

    这是在任何地方传递/指定的吗?

    【讨论】:

    • 您好 M Schenkel,感谢您的回复!我的重定向 uri 和你的一样,但我不明白你打电话给accounts.google.com/o/oauth2/auth 的意思。是否可以不提示该页面?我只想验证并获取站点的访问(现在是会话)。
    • 听起来我们有不同的实现/目标。 oAuth 的工作方式,或者至少我这样做的方式,是让用户“验证”。然后,Google 会为您提供“刷新令牌”。您使用此令牌获得持续 60 分钟的“短期”会话。您在通话中使用此令牌。但是,60 分钟后,您必须获得一个新令牌。听起来您想要一个解决方案,在每个会话上提示用户输入凭据。使用 oAuth,只需执行一次。
    • 您好 M Schenkel,我想要的是使用一个帐户来显示我网站的访问次数。只有这个。所以我不希望用户被提示一次凭据。 OAuth2 有可能吗?这是正确的方式吗?
    • 是的。当您说只想进行身份验证并获取站点的访问(现在是会话)时,听起来您的实现会提示在每个会话上进行身份验证。 oAuth2 是要走的路。但是您需要存储刷新令牌。而且,在此过程中,您必须通过 Google 进行身份验证才能执行此操作(尽管只有一次)。
    • 您好,M Schenkel!我终于成功了。我通过服务帐户身份验证来实现它。以及创建 Service Account 类型的客户 ID。我使用从该服务帐户生成的 P12 来验证和使用 GA API。看起来会话不需要 OAuth2。谢谢你的时间!最好的问候
    猜你喜欢
    • 2014-11-16
    • 2017-08-06
    • 2018-04-19
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    相关资源
    最近更新 更多