Acegiとの連携2
こちらをベースにしたらもっとずっとスマートに出来た
http://struts.apache.org/2.0.9/docs/can-we-use-acegi-security-with-the-framework.html
jp.co.hershe.struts2.acegi.AuthzInterceptor.java
package jp.co.hershe.struts2.acegi; import org.acegisecurity.AccessDeniedException; import org.acegisecurity.taglibs.velocity.Authz; import org.acegisecurity.taglibs.velocity.AuthzImpl; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; /** * ACEGI認可のメカニズムで実行されるアクションをチェックする為のインターセプタ * また AuthzAware がアクションに実装されていればAuthzオブジェクトをアクションに設定する * * @author mikuni * */ public class AuthzInterceptor implements Interceptor { String allowroles; String denyroles; public void destroy() {} public void init() {} /** * @param allowroles 許可されるロール カンマ区切り */ public void setAllowedRoles(String allowroles) { this.allowroles = allowroles; } /** * * @param denyroles 拒否されるロール カンマ区切り */ public void setDeniedRoles(String denyroles) { this.denyroles = denyroles; } public String intercept(ActionInvocation invocation) throws Exception { Object act = invocation.getAction(); if (allowroles != null || denyroles != null || act instanceof AuthzAware ) { Authz authz = new AuthzImpl(); // 認可チェック if (allowroles != null ) { if (!authz.anyGranted(allowroles)) { throw new AccessDeniedException("not allow"); } } if (denyroles != null ) { if (authz.anyGranted(denyroles)) { throw new AccessDeniedException("deny"); } } // Actionへの認可オブジェクトの設定 if (act instanceof AuthzAware) { AuthzAware authzAware = (AuthzAware)act; authzAware.setAuthz(authz); } } return invocation.invoke(); } }
こちらを struts.xml にインターセプタとして次のように登録
<interceptor name="login" class="jp.co.hershe.struts2.acegi.AuthzInterceptor"> <param name="deniedRoles">ROLE_ANONYMOUS</param> </interceptor> <interceptor name="require_role_user" class="jp.co.hershe.struts2.acegi.AuthzInterceptor"> <param name="allowedRoles">ROLE_USER</param> </interceptor>
などとすると認証チェックしてくれる