jooby + pac4j + Auth0でログイン認証してみる
諦めてSpringにしようかと思いつつ、丸C日頑張ってみた成果
このクラスを用意する。jooby + pack4jで必要になるクラス
public class Auth0Client extends GenericOAuth20StateClient { public Auth0Client(final String key, // Client IDのこと final String secret, // Client Secretのこと final String authUrl, // Advanced SettingsのOAuth Authorization URL final String tokenUrl, // Advanced SettingsのOAuth Token URL final String profileUrl, // Advanced SettingsのOAuth User Info URL final String scope) { // 任意だけど openid email nickname こんな感じで色々取れる super(key, secret, authUrl, tokenUrl, profileUrl, scope); } protected String getOAuthScope() { return getScope(); // 何故Genericなのに上書きしない・・・ } protected boolean hasOAuthGrantType() { return true; // GrantTypeを引数に渡す } @Override protected GenericOAuth20Profile extractUserProfile(String body) { final GenericOAuth20Profile profile = new GenericOAuth20Profile(); if (attributesDefinition != null) { profile.setAttributesDefinition(attributesDefinition); } final JsonNode json = JsonHelper.getFirstNode(body); if (json != null) { profile.setId(JsonHelper.getElement(json, "user_id")); // デフォルトはidなので変えたかっただけ for (final String attribute : profile.getAttributesDefinition().getPrimaryAttributes()) { profile.addAttribute(attribute, JsonHelper.getElement(json, attribute)); } } return profile; } }
基本的にdemoから色々取ってくるファイル群
html5.html,index.html,profile.html
あとAppからgetUserProfileもコピペ忘れずに
get("/", () -> Results.html("index")); use(new Auth() .client("/oauth/**", conf -> { return new Auth0Client( conf.getString("auth.clientId") , conf.getString("auth.clientSeacret") , conf.getString("auth.authorizeUrl") , conf.getString("auth.tokenUrl") , conf.getString("auth.userinfoUrl") , conf.getString("auth.scope") ); }) ); /** One handler for logged user. */ Route.OneArgHandler handler = req -> { UserProfile profile = getUserProfile(req); return Results.html("profile") .put("client", profile.getClass().getSimpleName().replace("Profile", "")) .put("profile", profile); }; get("/oauth", handler);
application.confにはこんな感じで書く
auth { # use default callback, require for oidc and others callback = "http://"${application.host}":"${application.port}${application.path}"callback" authorizeUrl = "https://xxxxxx.auth0.com/authorize" tokenUrl = "https://xxxxxxx.auth0.com/oauth/token" userinfoUrl = "https://xxxxxx.auth0.com/userinfo" clientId = "XXXXXXXXXXXXXXXXXXXXXX" clientSeacret = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY" scope = "openid email nickname" }
この状態で起動した後、 localhost:8080/oauth?client_name=Auth0Client を表示すると、Auth0の画面が出てくる
その場でアカウントを作ってログインしたりすると
profileページが出てきてメアドなどの情報がゲット出来る
これ、すぐ終わると思ったのに長かった・・・
本当はconfigの自動設定もできるんだけど、そこに興味ないのでやってないw