My Guice Integration Adventures: Building Secure RESTful Web Application with Apache Shiro

Intro & Motivation

From my previous post, I created an Maven Archetype to bootstrap a Java Web Application. My next step was to make the Web App Secure somehow, and by recommendation I came into Apache Shiro.

RBAC and Security Management

Apache Shiro has a new way of thinking security, with its Resource Based Access Control  (RBAC, not to be mistaken with Role Based Access Control). Basically, instead of giving access to Roles, you give set access to Resources, in this case RESTful endpoints. This can be applied to all JAX-RS Resources.

Second Approach: Guice + Apache Shiro + Jersey

The way to integrate Shiro into a web application is via the web filters to attach the Security Context into the main context. But I also needed to configure Guice, so it can load the Security Manager and Shiro Realms as Singletons at bootstrap.

I also used Shiro’s AOP Module to support Annotations like @RequiresPermission, but in the long run I stuck with the default way for requesting Permissions.

My overall experience with Shiro was very successful, and I found the Permission approach very intuitive. It’s very customizable also, having the chance to modify the behavior of Sessions (or go totally Sesion-less), Permission levels and Realms to save Users, Roles and Permissions according to your existing data structure.

Finally this framework also counts with a Cryptography package, to manage your passwords in multiple formats (MD5, SHA1, SHA-256, et al.) and to encrypt any kind of data to be shared.

Code Template Project

My github example is in shiro-guice-jersey-bootstrap project. This integrates the following frameworks and libraries:

  • Servlet 2.5
  • Jersey 1.18.1
  • Guice 3.0
  • Apache Shiro 1.2.3
  • guice-persist 3.0
  • gson 2.2.4
  • joda-time 2.4
  • JUnit 4.10

I also made a Maven Archetype from this template in secure-rest-webapp-archetype project.

Conclusions

This kind of projects are very demanded nowadays because of the SaaS and MBaaS architectures, and like I said in previous post, having Jersey makes your RESTful tier compliant with JAX-RS, Guice and Dependency Injection compliant with JSR-330 and the so long standardized Servlet 2.5 spec compliant with any Java Enterprise Application Servers. This makes the app more portable in terms of code sharing/reviewing and more focused on the BackEnd business logic, allowing a more agile workflow for distributed teams.

Next Adventure

My next adventure will involve RESTEasy and Servlet 3.x spec! Stay tuned!

Cheers!