您可以定义一个默认拦截器并在那里进行一些角色检查。
拦截器将是这样的:
public class LoginCheckInterceptor {
@Resource
private EJBContext ejbContext;
@AroundInvoke
public Object checkLogin(final InvocationContext context) throws Exception {
if (userAuthenticated()) {
return context.proceed();
} else {
throw new SecurityException("User not authorized");
}
}
private boolean userAuthenticated() {
// do role checking as needed
// use this.ejbContext.isCallerInRole(...)
// or this.ejbContext.getCallerPrincipal()
}
}
要使其作为默认拦截器工作(适用于所有 EJB),请自定义部署描述符ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar>
<interceptors>
<interceptor>
<interceptor-class>your.package.LoginCheckInterceptor</interceptor-class>
</interceptor>
</interceptors>
<assembly-descriptor>
<interceptor-binding>
<ejb-name>*</ejb-name>
<interceptor-class>your.package.LoginCheckInterceptor</interceptor-class>
</interceptor-binding>
</assembly-descriptor>
</ejb-jar>