Thursday, September 15, 2011

Using Spring Security with Ring, Jetty, and Compojure

All the source code for this can be found at https://github.com/lispnik/ring-spring-security

Spring Security (formerly Acegi Security) is a great framework for adding authentication and authorization to your Java web app. I wanted to take advantage of it in my Compojure apps. Here's an example of how to do it:



The next step is to wrap this in a ring/ring-adapter-jetty configurator (i.e., a function that takes a server):



To illustrate the integration, here is an example Spring Security configuration which establishes two users and two roles (user and administration) and applies it to URL patterns. If the user issues a HTTP request with a URL pattern that requires authorization and they are not already authenticated, then Spring Security as configured below will actually render a plain-looking login form before proceeding. We get this basic functionality for free with Spring Security although it can be replaced with a custom form of our own design.



The Compojure application this secures looks like this:



Here the HTML rendering prints out the Spring context and security context which contain lots of goodies we can use later: