1
votes

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

1 Answers

0
votes

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?enter image description here