アクセス制御
次に作成したUserInfoを用いて、アクセス制御機能を追加していきます。ここでは、ログインに成功した場合のみ以下のSecureServiceサービスにアクセスできるようにします。
package sample;
import org.springframework.stereotype.Service;
import com.curlap.orb.security.RemoteService;
@RemoteService
@Service("secure")
public class SecureService {
public String doSomething() {
return "Did something!!";
}
}
このSecureServiceには、ログイン済みの場合にはアクセス可能、未ログインの際にはアクセス不可という制御をかけることにします。こういった処理は通常SecureServiceだけではなく、多くのサービスを制御することとなるため、AOPを使い共通機能として作っていきます。
AOPを使って各メソッドの実行前にアクセスチェック機能を設けるため、MethodBeforeAdviceを継承したクラスを作成し、beforeメソッドを実装します。
package sample;
import java.lang.reflect.Method;
import javax.annotation.Resource;
import org.springframework.aop.MethodBeforeAdvice;
public class ServiceBeforeAdvice implements MethodBeforeAdvice {
@Resource
private UserInfo userInfo;
public void before(Method method, Object[] args, Object target) throws Throwable {
if (!userInfo.isHasLogined()) {
throw new AuthException("Authentication error!!");
}
}
}
ここでは、UserInfoのhasLoginedがfalseであれば、ログインに成功していないこととなるので、AuthExceptionという例外をスローするようにします。もしhasLoginedがtrueであれば、ログインに成功していますので、SecureServiceのメソッドにアクセスできるようにします。
package sample;
/*
* AuthException
* NOTE: extends RuntimeException due to AOP
*/
public class AuthException extends RuntimeException {
private static final long serialVersionUID = 1L;
public AuthException() {
super();
}
public AuthException(String message) {
super(message);
}
public AuthException(String message, Throwable rootCause) {
super(message, rootCause);
}
public AuthException(Throwable rootCause) {
super(rootCause);
}
}
AuthExceptionは、RuntimeExceptionを継承したクラスです。
このServiceBeforeAdviceをSpringの設定ファイル(applicationContext.xml)に設定するため、以下の行を追加します。
<aop:config>
<aop:advisor pointcut="execution(* sample.SecureService.*(..))"
advice-ref="before"/>
</aop:config>
<bean id="before" class="sample.ServiceBeforeAdvice" />
もし、SecureService以外のサービスも追加するには上記のpointcutを修正してください。
これで、認証とアクセス制御の機能ができました。web.xmlに以下のリスナーを追加して、サーバを起動してください。
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

