Apache Shiro is a Java framework to simply authentication, authorization etc. I previously blogged about a test-case I wrote that shows how to use Shiro with Apache CXF to authenticate and authorize a username and password received as part of a web service request. This post extends the previous post by showing how to use Shiro to enable authorization via annotations on the service implementation.
The previous post defined some required roles for an endpoint in Spring, and passed them through to a ShiroUTValidator class which checks that the authenticated subject has all of the defined roles:
The problem with this approach is that it's not possible to specify individual roles for different methods in the service implementation - the user must have the role to invoke on any of the methods.
An alternative is instead to use Shiro's annotation support. Here we can add annotations to the service endpoint implementation to require that the authenticated user has the correct role (@RequiresRoles) or permissions (@RequiresPermissions). Note that these annotations are specific to Shiro, support is not yet added to support the standard javax.annotation.security annotations (see here).
So to change our test-case to use annotations, instead of defining the roles in Spring, we instead define the following annotation in the service implementation:
In the spring configuration for the service, we need to add a few additional interceptors so that the annotation gets processed:
That's all that's required to get Shiro annotations working with CXF service implementations. The full test source is available here.