giovedì 28 aprile 2011

Jersey, @RolesAllowed annotation and 403 Forbidden

I spent last three hours to understand why I always get 403 Forbidden from a secured JAX-RS resource with @RolesAllowed...
After checking the params of Jersey Servlet:

 <init-param>  
  <param-name>com.sun.jersey.spi.container.ResourceFilters</param-name>  
  <param-value>com.sun.jersey.api.container.filter.RolesAllowedResourceFilterFactory</param-value>  
 </init-param>  

I proceeded to debug the filter under the hood, RolesAllowedResourceFilterFactory, and I noticed that UserPrincipal was null!
What I'd forgotten was to secured the resources with security-constraint:

 <security-constraint>  
  <web-resource-collection>  
   <web-resource-name>Protected Area</web-resource-name>  
   <url-pattern>/resources/*</url-pattern>  
  </web-resource-collection>  
  <auth-constraint>  
   <role-name>admin</role-name>  
   <role-name>user</role-name>  
  </auth-constraint>  
 </security-constraint>  

In role-name you've to insert all the roles that you're going to use in @RolesAllowed.

Good night!