Reputation: 5043
Question: Where is the implementation for JavaEE6?
I'm currently working on a JavaEE6 project and I found out that Shiro's annotation is not working out of the box even though I already configured web.xml and shiro.ini base on the documentation.
This is what I have:
1.) A page:
<h:form>
<h:commandLink action="#{userBean.action1()}" value="Action 1"></h:commandLink>
</h:form>
2.) Backing bean:
@Stateless
@Named
public class UserBean {
@Inject
private Logger log;
@RequiresAuthentication
public void action1() {
log.debug("action.1");
}
}
3.) web.xml
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>
<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ShiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
4.) shiro.ini
[main]
# listener = org.apache.shiro.config.event.LoggingBeanListener
shiro.loginUrl = /login.xhtml
[users]
# format: username = password, role1, role2, ..., roleN
root = secret,admin
guest = guest,guest
presidentskroob = 12345,president
darkhelmet = ludicrousspeed,darklord,schwartz
lonestarr = vespa,goodguy,schwartz
[roles]
# format: roleName = permission1, permission2, ..., permissionN
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5
[urls]
# The /login.jsp is not restricted to authenticated users (otherwise no one could log in!), but
# the 'authc' filter must still be specified for it so it can process that url's
# login submissions. It is 'smart' enough to allow those requests through as specified by the
# shiro.loginUrl above.
/login.xhtml = authc
/logout = logout
/account/** = authc
/remoting/** = authc, roles[b2bClient], perms["remote:invoke:lan,wan"]
But when I click the button, it still performs the action. It should throw unauthorizede exception right? The same is true with other shiro annotations.
Note that if I manually performs the check, it works:
public void action1() {
Subject currentUser = SecurityUtils.getSubject();
AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
currentUser.login(token);
log.debug("user." + currentUser);
if (currentUser.isAuthenticated()) {
log.debug("action.1");
} else {
log.debug("not authenticated");
}
}
Thanks,
czetsuya
Upvotes: 3
Views: 3279
Reputation: 1108537
You basically need a Java EE interceptor in order to scan for the annotations on the invoked CDI and EJB methods.
First create an annotation which the interceptor has to intercept on:
@Inherited
@InterceptorBinding
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ShiroSecured {
//
}
Then create the interceptor itself:
@Interceptor
@ShiroSecured
public class ShiroSecuredInterceptor implements Serializable {
private static final long serialVersionUID = 1L;
@AroundInvoke
public Object interceptShiroSecurity(InvocationContext context) throws Exception {
Class<?> c = context.getTarget().getClass();
Method m = context.getMethod();
Subject subject = SecurityUtils.getSubject();
if (!subject.isAuthenticated() && hasAnnotation(c, m, RequiresAuthentication.class)) {
throw new UnauthenticatedException("Authentication required");
}
if (subject.getPrincipal() != null && hasAnnotation(c, m, RequiresGuest.class)) {
throw new UnauthenticatedException("Guest required");
}
if (subject.getPrincipal() == null && hasAnnotation(c, m, RequiresUser.class)) {
throw new UnauthenticatedException("User required");
}
RequiresRoles roles = getAnnotation(c, m, RequiresRoles.class);
if (roles != null) {
subject.checkRoles(Arrays.asList(roles.value()));
}
RequiresPermissions permissions = getAnnotation(c, m, RequiresPermissions.class);
if (permissions != null) {
subject.checkPermissions(permissions.value());
}
return context.proceed();
}
private static boolean hasAnnotation(Class<?> c, Method m, Class<? extends Annotation> a) {
return m.isAnnotationPresent(a)
|| c.isAnnotationPresent(a)
|| c.getSuperclass().isAnnotationPresent(a);
}
private static <A extends Annotation> A getAnnotation(Class<?> c, Method m, Class<A> a) {
return m.isAnnotationPresent(a) ? m.getAnnotation(a)
: c.isAnnotationPresent(a) ? c.getAnnotation(a)
: c.getSuperclass().getAnnotation(a);
}
}
Note that the annotations are checked on the target class' superclass as well as the target class may in case of CDI actually be a proxy and Shiro's annotations don't have @Inherited
set.
In order to get it to work on CDI managed beans, first register the interceptor in /WEB-INF/beans.xml
as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://docs.jboss.org/cdi/beans_1_0.xsd"
>
<interceptors>
<class>com.example.interceptor.ShiroSecuredInterceptor</class>
</interceptors>
</beans>
Similarly, in order to get it to work on EJBs, first register the interceptor in /WEB-INF/ejb-jar.xml
as follows (or in /META-INF/ejb-jar.xml
if you've a separate EJB project in EAR):
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd"
version="3.1"
>
<interceptors>
<interceptor>
<interceptor-class>com.example.interceptor.ShiroSecuredInterceptor</interceptor-class>
</interceptor>
</interceptors>
<assembly-descriptor>
<interceptor-binding>
<ejb-name>*</ejb-name>
<interceptor-class>com.example.interceptor.ShiroSecuredInterceptor</interceptor-class>
</interceptor-binding>
</assembly-descriptor>
</ejb-jar>
On a CDI managed bean, you need to set the custom @ShiroSecured
annotation in order to get the interceptor to run.
@Named
@RequestScoped
@ShiroSecured
public class SomeBean {
@RequiresRoles("ADMIN")
public void doSomethingWhichIsOnlyAllowedByADMIN() {
// ...
}
}
This is not necessary on an EJB, the ejb-jar.xml
has already registered it on all EJBs.
Upvotes: 4
Reputation: 5043
Basically, what I'm missing is the implementation for Shiro's Requires* interfaces so I implemented depending on my needs. For those of you who are interested you can find it here: http://czetsuya-tech.blogspot.com/2012/10/how-to-integrate-apache-shiro-with.html
Upvotes: -2