Baher FARAG
Baher FARAG

Reputation: 21

My Issue with Google Authentication

I have been using the old version of Google Calendar GData API (v1, v2) since November 2011 in my ASP.NET Applications, allowing Users to retrieve and/or create Calendar Events after submitting their usernames and passwords , and this was working perfectly till 17th of November 2014 just before Google decided to shut down this version of API as announced Calendar GData API / Google Calendar Connectors deprecation

Now I am stuck with the new version of Google APIS Calendar (v3) which forces me to use different scenario of Authentication Process instead of the Traditional one. I don't mind at all using this version of Calendar API as it supports all the needed features but now i don't know how to handle multiple users authentication to use their User Client's ID and Secret which are registered per each user Code Console.

So my question is : Is there any way to let user sign in with his/her normal credentials (Either by Username/Password or Google+ Sign UP feature) and bypassing the process of creating API Project, Enabling the needed APIs and creating new User credentials inside the Console through ASP.net code?

Any Sample code made in C# ASP.net is highly appreciated .

EDIT: Here is my code of Authentication I use

public static CalendarService Authenticate()
        {
            CalendarService service;
            GoogleAuthorizationCodeFlow flow;
            string json_File = System.Configuration.ConfigurationManager.AppSettings["Authentication_Path"];
            string store_path = System.Configuration.ConfigurationManager.AppSettings["FileStore_Path"];
            string url = System.Configuration.ConfigurationManager.AppSettings["Authent_URL"];

            using (var stream = new FileStream(json_File, FileMode.Open, FileAccess.Read))
            {
                flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    DataStore = new FileDataStore(store_path),
                    ClientSecretsStream = stream,
                    Scopes = new[] { CalendarService.Scope.Calendar }
                });
            }
            var uri = url;

            var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync("TRAININGCALENDAR", CancellationToken.None).Result;
            if (result.Credential == null)
            {
                GoogleCalendar_Bus.Main_Authentication(url, "", "");
            }
            // The data store contains the user credential, so the user has been already authenticated.
            service = new CalendarService(new BaseClientService.Initializer
            {
                ApplicationName = "Calendar API Sample",
                HttpClientInitializer = result.Credential
            });
            if (result.Credential != null)
            {
                service = new CalendarService(new BaseClientService.Initializer
                {
                    ApplicationName = "Calendar API Sample",
                    HttpClientInitializer = result.Credential
                });
            }

            return service;
        }

Upvotes: 0

Views: 658

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117301

No you need to use Oauth2. When they authenticate you just save the refresh token this will allow you to then get a new access token and you will have access again. You will need to make your own implementation of Idatastore to store these refresh tokens in the database.

The code for creating an implementation of a Idatastore that stores to the Database is to extensive to post here but you can see a basic example here: DatabaseDataStore.cs

Then you can use it like this.

credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new ClientSecrets { ClientId = _client_id
                                       ,ClientSecret = _client_secret }
                    ,scopes
                    ,Environment.UserName
                     ,CancellationToken.None
                     ,new DatabaseDataStore(@"LINDAPC\SQL2012", "LindaTest", "test123", "test", "test")).Result;

Update: Now that I can see your code.

  1. Make sure you have the latested .net client lib. Google.Apis.Calendar.v3 Client Library
  2. your code is using FileDataStore this is what you will need to change. You need to make your own implementation of Idatastore similar to the one I have created DatabaseDatastore.

Your code looks different from how I normally do it.

string[] scopes = new string[] {
        CalendarService.Scope.Calendar  ,  // Manage your calendars
        CalendarService.Scope.CalendarReadonly    // View your Calendars
            };

            try
            {
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                    , scopes
                                                                    , userName
                                                                    , CancellationToken.None
                                                                    , new FileDataStore("Daimto.GoogleCalendar.Auth.Store")).Result;



                CalendarService service = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Calendar API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }

This may be due to the fact that you aren't using the most up to date client lib, you can find a sample console application for Google Calendar here unfortunately it also uses FileDatastore you will have to edit it to use DatabaseDataStore. The authentication sample project can be found here Google-Dotnet-Samples/Authentication/ it shows how you can create your own implementation of Idatastore.

I am still working on the tutorial to go along with that sample project I hope to have it completed soon.

Upvotes: 2

Related Questions