Seasar2での認証の方法

Seasar2を使用している場合、認証の方法をどのように実装しようか迷う。
今までは、Interceptorで認証を実装していたが、Validatorの方が先に動作するために、正常な認証は出来ない。。
Filter、RequestProcessor等で実装も考えたが、やはり楽に(DIの恩恵を受けれて)実装できるInterceptorの方がよい!
そんな時に、sastruts-extensionを知った。
これを使用すれば、Validatorが動作する前に、認証のロジックを動作させることが可能になった。

実装方法は以下。

まず、認証のロジックを作る。

AuthenticationProxy.java

public class AuthenticationProxy implements ActionProxy {

    /** 認証ロジック */
    @Resource
    protected AuthenticationLogic authenticationLogic;

    /**
     * {@inheritDoc}
     */
    @Override
    public String execute(ProxyChain proxyChain) throws Exception {
        if (authenticationLogic.isLogined()) {
            return proxyChain.invoke();
        }
        return "/login/";
    }
}

proxyパッケージの配下に作ること。
ActionProxyをimplementsして、executeメソッド内で、認証を実装すればよい。認証が通れば、ProxyChain#invokeを返し、通らなければ、ログイン画面のパスを返す。

これらをDIするために、下記の設定ファイルを変更する。

creator.dicon

<component class="jp.ardito.seasar.struts.creator.ProxyCreator"/>

ProxyCreatorのコンポーネント定義を追加。

customizer.dicon

<component name="actionCustomizer" class="org.seasar.framework.container.customizer.CustomizerChain">
<initMethod name="addAspectCustomizer">
  <arg>"aop.traceInterceptor"</arg>
</initMethod>
<initMethod name="addAspectCustomizer">
  <arg>"actionMessagesThrowsInterceptor"</arg>
  <arg>true</arg>
</initMethod>
<initMethod name="addCustomizer">
  <arg>
    <component class="org.seasar.framework.container.customizer.TxAttributeCustomizer" />
  </arg>
</initMethod>
<initMethod name="addCustomizer">
  <arg>
    <component class="jp.ardito.seasar.struts.customizer.A3ActionCustomizer">
      <initMethod name="addGlobalProxyClass">
        <arg>@apps.proxy.AuthenticationProxy@class</arg>
      </initMethod>
    </component>
  </arg>
</initMethod>
</component>
<component name="proxyCustomizer" class="org.seasar.framework.container.customizer.CustomizerChain"/>

A3ActionCustomizerの設定と、proxyCustomizerのコンポーネント定義を追加。

struts-config.xml

<controller
    maxFileSize="1024K"
    bufferSize="1024"
    processorClass="jp.ardito.seasar.struts.action.A3RequestProcessor"
    multipartClass="org.seasar.struts.upload.S2MultipartRequestHandler"/>

認証のロジックを実行させるために、A3RequestProcessorに変更。

実際のAction。

IndexAction.java

public class IndexAction {

    @Proxy(type = ProxyType.APPEND, proxy = AuthorizationProxy.class)
    @Execute(validator = false)
    public String execute1() {
        ...
    }

    @Proxy(type = ProxyType.DEFAULT)
    @Execute(validator = false)
    public String execute2() {
        ...
    }

    @Proxy(type = ProxyType.NONE)
    @Execute(validator = false)
    public String execute3() {
        ...
    }

    @Proxy(type = ProxyType.OVERRIDE, proxy = AuthorizationProxy.class)
    @Execute(validator = false)
    public String execute4() {
        ...
    }
}

適用方法は、Proxyアノテーションを使う。
デフォルトは、ProxyType.DEFAULTなので、記述しなければ、適用される。
Proxyアノテーションについてはサイトを参照のこと。

これで、Validatorの前に実行される認証のロジックが出来る。
なんて簡単!!!