2011年10月23日日曜日

.NET(C#) でGoogleOAuthを行なってみる。


IS12Tを手にいれたけど、何かアプリつくろう!って思って考えてたら
Google+のクライアントがないことに気づいたのでそれを作ってみようと思う。


サンプルを読み込む


とにかくOAuthアクセスを実現する必要があるはずなので
まずはサンプルを取得してきます。

https://developers.google.com/+/downloads
http://code.google.com/p/google-api-dotnet-client/





ここにサンプルとあるのでそれを取得。
※各種OAuthとかの文章ありますけど、ソースとかが古かったりですね。

「Tasks.SimpleOAuth2」というプロジェクトがコンソールでできるやつみたいなので
そちらをスタートプロジェクトにして実行するわけですけど、
「Google.Apis.Samples.TasksOAuth2.ClientCredentials」に
APIキーの設定のがあるの以下のように設定します。



  1.         public static readonly string ClientID = "xxxxxxxx.apps.googleusercontent.com";  
  2.   
  3.   
  4.   
  5.         /// <summary>  
  6.   
  7.         /// The OAuth2.0 Client secret of your project.  
  8.   
  9.         /// </summary>  
  10.   
  11.         public static readonly string ClientSecret = "xxxxxxxxxxxxxxxxlOd2y";  
  12.   
  13.   
  14.   
  15.         /// <summary>  
  16.   
  17.         /// Your Api/Developer key.  
  18.   
  19.         /// </summary>  
  20.   
  21.         public static readonly string ApiKey = "urn:xxxxxxxxxx";  





OAuth用の準備


https://code.google.com/apis/console

に行ってGoogle+APIをONにしておきます。




今は「Courtesy limit: 1,000 queries/day」なので
1日1000回のアクセスまでのようですね。。。。ん?ユーザじゃなくてAPIキーでかな?

API AccessのところにOAuth2.0があるのでそこでキーを発行します。
OAuthでお馴染みのClientIDとSecretですね。






Google PlusのAPIを使ってみる

このサンプルはTasks APIの
PlusのDLLはBinaryサンプルのServiceの中にあります。
これを参照設定して追加してPlusServiceを使えるようにしておきます。

  1.             // Display the header and initialize the sample.  
  2.   
  3.             CommandLine.EnableExceptionHandling();  
  4.   
  5.             CommandLine.DisplayGoogleSampleHeader("Google+ API");  

コンソールにGoogleのロゴを出す部分ですね。特に大事なコードではないです。
一応TaskになっていたのでGoogle+に変更。


  1.             // Register the authenticator.  
  2.   
  3.             var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);  
  4.   
  5.             provider.ClientIdentifier = ClientCredentials.ClientID;  
  6.   
  7.             provider.ClientSecret = ClientCredentials.ClientSecret;  
  8.   
  9.             var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);  


ここでClientIDとSecretを使ってURLを作成している処理です。
GetAuthrorizarionは、サンプルであるProgram.csにあります。


  1.         private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)  
  2.   
  3.         {  
  4.   
  5.             // Get the auth URL:  
  6.   
  7.             IAuthorizationState state = new AuthorizationState(new[] { PlusService.Scopes.PlusMe.GetStringValue() });  
  8.   
  9.             state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);  
  10.   
  11.             Uri authUri = arg.RequestUserAuthorization(state);  
  12.   
  13.   
  14.   
  15.             // Request authorization from the user (by opening a browser window):  
  16.   
  17.             Process.Start(authUri.ToString());  
  18.   
  19.             Console.Write("  Authorization Code: ");  
  20.   
  21.             string authCode = Console.ReadLine();  
  22.   
  23.             Console.WriteLine();  
  24.   
  25.   
  26.   
  27.             // Retrieve the access token by using the authorization code:  
  28.   
  29.             return arg.ProcessUserAuthorization(authCode, state);  
  30.   
  31.         }  





NativeApplicationClient を元にOAuthにアクセスするURLを作成していきます。
IAuthorizarionStateでTasksのGetStringValue()を読んでいるのでPlusServiceにしてあげます。
実行するとこんな感じです。


ReadLine()でOAuthの認証コードを待ち受けます。
※実際の実行タイミングはFetch()するまでアクセスはされません。

Process.Start()で作成したURLにアクセスしますのでこれと同時にブラウザが立ちあがってるはずです。


アクセスを許可するとキーが発行されるのでそれをコンソールにコピペして、Enterします。
タスクに対して




  1.             var service = new PlusService(auth);  
  2.   
  3.             Person me = service.People.Get("me").Fetch();  
  4.   
  5.             CommandLine.WriteLine("     ^2" + me.Name);  
  6.   
  7.   
  8.   
  9.             ActivitiesResource.Collection collection = new ActivitiesResource.Collection();  
  10.   
  11.             ActivityFeed feed = service.Activities.List("me",collection).Fetch();  
  12.   
  13.             foreach (Activity list in feed.Items)  
  14.   
  15.             {  
  16.   
  17.                 CommandLine.WriteLine("     ^2" + list.Title);  
  18.   
  19.             }  
  20.   
  21.             CommandLine.PressAnyKeyToExit();  




と行なってみたら、自分の投稿を取得できました。
はじめ自分のIDを指定して検索してたんですが
「うんなもんOAuthじゃねーヽ(`Д´)ノプンプン」だったんですけど"me"で取得できました。

一旦これでアクセス自体はできたみたいですね。

途中、OAuthとGoogle+のAPIと.NETのAPIを読んでいてパニック起こしました。
誰がどれを作っているのかわからなくなったからです。

上位のクラスとか結構しっかり作ってある感じなので
簡単にOAuth(Google+API)にアクセスすることができます。

これをネタにWindowsPhoneクライアントを作るっていう大きな作業が待ってます。

0 件のコメント: