Home > Java | Web > Play FrameworkでOAuth認証利用 その4:はてな

Play FrameworkでOAuth認証利用 その4:はてな

  • 2011-12-19 (月) 1:43
  • Java | Web

 前回の続きで、今晩の最後。はてなアカウントによる認証を実装します。
 また、とりあえず、Twitter、Facebook、Google、はてなのアカウントで、OAuth認証ができるようになったの、Aplication.java/index.htmlも適当に編集します。
 Play組み込みのライブラリのおかげで、簡単にOAuth認証が実装できました。
 → サンプルページ

5.はてな

 はてなアカウントによるOAuth認証を実装します。
 リソースはこの辺りです。
 はてなのOAuthは、ver.1.0で、Googleと同様、独自拡張で”scope”というパラメータが必要になります。

1)アプリケーションの登録

 はてなのOAuth 開発者向け設定ページで、アプリケーションを登録しました。

2)HatenaAuth.javaの実装

 HatenaAuth.javaは、GoogleAuth.javaとほぼ同じコードで実装しました。

package controllers;

import java.util.HashMap;
import java.util.Map;

import models.User;
import play.Logger;
import play.libs.OAuth;
import play.libs.OAuth.ServiceInfo;
import play.libs.WS;
import play.mvc.Controller;

import com.google.gson.JsonObject;

public class HatenaAuth extends Controller {

	private static final ServiceInfo HATENA = new ServiceInfo(
			"https://www.hatena.com/oauth/initiate?scope=read_public",
			"https://www.hatena.com/oauth/token",
			"https://www.hatena.ne.jp/oauth/authorize",
			"**************************",
			"**************************"
	);

	public static void authenticate() {
		User user = getUser();
		if (OAuth.isVerifierResponse()) {
			OAuth.Response oauthResponse = OAuth.service(
				HATENA).retrieveAccessToken(user.token, user.secret);
			if (oauthResponse.error == null) {
				user.token = oauthResponse.token;
				user.secret = oauthResponse.secret;
				user.save();
			} else {
				Logger.error("Error connecting to hatena: " + oauthResponse.error);
			}
			Application.index();
		}
		OAuth twitt = OAuth.service(HATENA);
		OAuth.Response oauthResponse = twitt.retrieveRequestToken();
		if (oauthResponse.error == null) {
			user.token = oauthResponse.token;
			user.secret = oauthResponse.secret;
			user.save();
			redirect(twitt.redirectUrl(oauthResponse.token));
		} else {
			Logger.error("Error connecting to hatena: " + oauthResponse.error);
			Application.index();
		}
	}

	public static Map<String,String> getUserInfo(){
		Map<String,String> ret=new HashMap<String,String>();
		User u=getUser();
		JsonObject me = null;
		if (u != null && u.token!=null){
			ret.put("auth", "hatena");
			me = WS.url("http://n.hatena.com/applications/my.json").oauth(HATENA,
				 getUser().token, getUser().secret).get().getJson().getAsJsonObject();
			Object o=me.get("url_name");
			if(o!=null){
				String ss=o.toString().replace("\"", "");
				ret.put("name",ss);
			}
			o=me.get("display_name");
			if(o!=null){
				String ss=o.toString().replace("\"", "");
				ret.put("screenname",ss);
			}
			o=me.get("profile_image_url");
			if(o!=null){
				String ss=o.toString().replace("\"", "");
				ret.put("imageurl",ss);
			}
		}
		return ret;
	}

	public static User getUser() {
		return User.findOrCreate("guest");
	}
}

6.認証ページの編集

 Application.javaを編集し、認証ページのサンプルを作成しました。
 今回は練習用なので、アカウントのDB登録等はせず、上から順番に認証を確認し、認証されていた場合はアイコンとID名を表示するという、ごく簡単なものとしました。

1)Application.java

 コントローラーであるApplication.javaは以下のとおり実装。
 Facebookのユーザー名取得の関係で、setuserメソッドを実装しています。

package controllers;

import java.util.Map;

import models.User;
import play.Logger;
import play.libs.OAuth;
import play.libs.OAuth.ServiceInfo;
import play.mvc.Before;
import play.mvc.Controller;

public class Application extends Controller {

	public static void index() {
		Map<String,String> userinfo=TwitterAuth.getUserInfo();
		if(userinfo.get("auth")==null){
			userinfo=GoogleAuth.getUserInfo();
		}
		if(userinfo.get("auth")==null){
			userinfo=FacebookAuth.getUserInfo();
		}
		if(userinfo.get("auth")==null){
			userinfo=HatenaAuth.getUserInfo();
		}
		render(userinfo);
	}

	@Before
	static void setuser() {
		User user = null;
		if (session.contains("uid")) {
			Logger.info("existing user: " + session.get("uid"));
			user = User.get(Long.parseLong(session.get("uid")));
		}
		if (user == null) {
			user = User.createNew();
			session.put("uid", user.uid);
		}
		renderArgs.put("user", user);
	}
}

2)index.htmlの実装

 index.htmlは以下のとおりとしました。

#{extends 'main.html' /}
#{set title:'Home' /}

<h2>Twitter Authentication</h2>
#{if "twitter".equals(userinfo.get("auth"))}
<p><img src='${userinfo.get("imageurl")}' width="32px"
	 hspace="10px" align="bottom" />${userinfo.get("screenname")}</p>
#{/if}
#{else}
<a href="@{TwitterAuth.authenticate()}">
	<img src="public/images/sign_twitter.png" /></a>
#{/else}
<h2>Google Authentication</h2>
#{if "google".equals(userinfo.get("auth"))}
<p><img src='${userinfo.get("imageurl")}' width="32px"
	 hspace="10px" align="bottom" />${userinfo.get("screenname")}</p>
#{/if}
#{else}
<a href="@{GoogleAuth.authenticate()}">
	<img src="public/images/sign_google.png"  /></a>
#{/else}

<h2>Facebook Authentication</h2>
#{if "facebook".equals(userinfo.get("auth"))}
<p><img src='${userinfo.get("imageurl")}' width="32px"
	 hspace="10px" align="bottom" />${userinfo.get("screenname")}</p>
#{/if}
#{else}
<a href="@{FacebookAuth.authenticate()}">
	<img src="public/images/sign_facebook.png"  /></a>
#{/else}

<h2>Hatena Authentication</h2>
#{if "hatena".equals(userinfo.get("auth"))}
<p><img src='${userinfo.get("imageurl")}' width="32px"
	 hspace="10px" align="bottom" />${userinfo.get("screenname")}</p>
#{/if}
#{else}
<a href="@{HatenaAuth.authenticate()}">
	<img src="public/images/sign_hatena.png"  /></a>
#{/else}

7.所 感

 今回作成したサンプルは、こちら(サンプルページ)で動かしています。※playのテスト用なので、近日中に停止予定。

 まだ、OAuth系しかさわっていませんが、意外とPlayの組み込みライブラリが便利です。また、Playは、Eclipse上でJavaコードをコンパイルする必要がないため、動作確認や修正にストレスが少ないのが良いです。

 個人的には、Play Framework、期待以上におもしろいです。

Related posts:

  1. Play FrameworkでOAuth認証利用 その1:Twitter
  2. Play FrameworkでOAuth認証利用 その3:Google
  3. Play FrameworkでOAuth認証利用 その2:Facebook
  4. Play framework
  5. Project Euler Problem79 #ProjectEuler

Comments:0

Comment Form
Remember personal info

Trackbacks:0

Trackback URL for this entry
http://termat.sakura.ne.jp/java/play-framework%e3%81%a7oauth%e8%aa%8d%e8%a8%bc%e5%88%a9%e7%94%a8%e3%80%80%e3%81%9d%e3%81%ae4%ef%bc%9a%e3%81%af%e3%81%a6%e3%81%aa/trackback/?_wpnonce=4b3f1a9996
Listed below are links to weblogs that reference
Play FrameworkでOAuth認証利用 その4:はてな from TM's Workspace

Home > Java | Web > Play FrameworkでOAuth認証利用 その4:はてな

Google Analyticator

119
Unique
Visitors
Powered By Google Analytics

Return to page top