Skip to content

Instantly share code, notes, and snippets.

@hakobera hakobera/Auth.java
Created Dec 27, 2011

Embed
What would you like to do?
Play Framework で OpenID に接続して、認証後のユーザ情報をセッションに格納するサンプルコード
package controllers;
import models.Account;
import play.libs.OpenID;
import play.libs.OpenID.UserInfo;
import play.mvc.Before;
import play.mvc.Controller;
import play.mvc.With;
/**
* 認証フィルター的コントローラです。 認証が必要なコントローラ、メソッドは {@link With} アノテーションでこのクラスを指定します。
*/
public class Auth extends Controller {
private static final String SESSION_KEY = "account";
@Before(unless = { "login", "auth", "logout" })
static void begin() {
if (!isLoggedIn()) {
auth();
}
}
public static void auth() {
if (OpenID.isAuthenticationResponse()) {
// Postback from OpenID provider.
UserInfo verifiedUserInfo = OpenID.getVerifiedID();
if (verifiedUserInfo != null) {
// Store verifiedUserInfo.id
if (verifiedUserInfo.extensions != null) {
Account account = new Account();
account.id = verifiedUserInfo.id;
account.name = verifiedUserInfo.extensions.get("fullname");
login(account);
redirect("Application.index");
} else {
renderText("Logged in. Failed to get attributes");
}
} else {
renderText("Failed to log in.");
}
} else {
// Render login form.
render();
}
}
/**
* OpenID 認証サーバに対して、ログインリクエストを送信します。
*/
public static void login() {
String openIdURL = params.get("openid_url");
OpenID openIdReq = OpenID.id(openIdURL);
// Attribute Exchange (AX)
openIdReq.required("email", "http://axschema.org/contact/email");
openIdReq.required("firstName", "http://axschema.org/namePerson/first");
openIdReq.required("lastName", "http://axschema.org/namePerson/last");
// Perform redirect
openIdReq.verify();
}
/**
* ログアウトします。
*/
public static void logout() {
session.clear();
redirect("Application.index");
}
private static boolean isLoggedIn() {
return session.contains(SESSION_KEY);
}
private static void login(Account account) {
session.put(SESSION_KEY, account.id);
session.put("accountName", account.name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.