Wicketユーザ認証(1)

ユーザ認証して一連のページにアクセスさせることをWicket で試してみた。
作成するページクラスに、アノテーションでロール(Role)名を付けて
ページ表示制限できることが良い。

用意するもの(長いので3回に分割して投稿)

Wicket で約束の WebApplication は、AuthenticatedWebApplication を使う。
・ログイン画面のPageクラスを返す、getSignInPageClass() 
Wicket認証用セッション AuthenticatedWebSession 継承クラスを返す、
 getWebSessionClass()
・認証失敗時、ロール権限不一致時に実行する処理 onUnauthorizedPage 
これらを実装する

import org.apache.wicket.Application;
import org.apache.wicket.Page;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.authentication.AuthenticatedWebApplication;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.guice.GuiceComponentInjector;
import org.apache.wicket.markup.html.WebPage;

public class UranApplication extends AuthenticatedWebApplication{
   @Override
   protected void init(){
      super.init();
      //
   }
   @Override
   public Class<? extends Page> getHomePage(){
      return IndexPage.class;
   }
   @Override
   protected Class<? extends WebPage> getSignInPageClass(){
      return LoginPage.class;
   }

   @Override
   protected Class<? extends AuthenticatedWebSession> getWebSessionClass(){
      return UranSession.class;
   }
   @Override
   public void onUnauthorizedPage(Page page){
      throw new RestartResponseAtInterceptPageException(ErrorPage.class);
   }

}

--------------------------------------------------------------------
AuthenticatedWebSession を継承した例、

import jp.austin.auth.AuthManager;
import jp.austin.entity.Account;
import org.apache.wicket.Request;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.Roles;

public class UranSession extends AuthenticatedWebSession{
   private static final long serialVersionUID = 1L;
   private Roles roles;
   private Account account;
   
   public UranSession(Request request){
      super(request);
   }
   @Override
   public boolean authenticate(String username,String password){

      // 認証実行を行う、AuthManager は任意の処理
      this.account = AuthManager.getInstance().queryAuthenticate(username,password);
      if (this.account != null){
         // 認証成功、ロールを作成する
         this.roles = new Roles(this.account.role);
         return true;
      }
      this.roles = null;
      return false;
   }

   @Override
   public Roles getRoles(){
      return this.roles;
   }

   /**
    * Account取得 このメソッドは任意の処理で画面表示のため。
    * @return 認証済みのAccount
    */

   public Account getAccount(){
      return this.account;
   }
}