domenica, settembre 18, 2011

How to get users list from Google Apps using OAuth and C#

Recently I've added support for Google Apps to GDocBackup. Using a domain administrator username+password it retrieves users list and then backups all documents for each user. The backup is executed using the OAuth domanin keys. So GDocBackup uses two different authentication method: username+password and OAuth.  I don't like that. I'd like to use OAuth for both tasks. After some tests, internet search and the help of Claudio Cherubino, I've done a working application.
This is a very quick step-by-step guide on how I used OAuth.

Step 1 : activate OAuth for your domain. Go to domain control panel -> Advanced tools -> Manage OAuth domain key and activate the key.


Step 2 : enable readonly Provisioning API.  Go to domain control panel -> Advanced tools -> Manage third party OAuth Client access.  Under [Client Name] add your full domain name. Under [One or more api scopes] add https://apps-apis.google.com/a/feeds/user/#readonly. Then press [Authorize].


Step 3 : download the official Google GData library for .NET: http://code.google.com/p/google-gdata/

Step 4 : create a C# application with Visual Studio, add the required DLL from Google GData library and write a piece of code like the following. It will retrieve all user login.



string mydomain = "___mydomain___";
string myOAuthConsumerSecret = "___mysecretkey___";


GOAuthRequestFactory reqF = new GOAuthRequestFactory("apps", "mytestapp");
reqF.ConsumerKey = mydomain;
reqF.ConsumerSecret = myOAuthConsumerSecret;


UserService userService = new UserService("mytestapp");
userService.RequestFactory = reqF;


UserQuery query = new UserQuery(mydomain, true);
UserFeed usersFeed = userService.Query(query);
foreach (UserEntry entry in usersFeed.Entries)
    Console.WriteLine(entry.Login.UserName);



[Update]
Details about API authorization: http://www.google.com/support/a/bin/answer.py?answer=162106



Nessun commento: