Barebones Spring MVC part 5: Security

August 19, 2010

A web application would seldom be complete without at least a minimal security layer to prohibit unauthenticated access to protected resources.

This example builds upon part 1: core to introduce basic security by adding a form-based login page using Spring Security.

The following changes are required:

  1. Add Spring Security to the Maven POM.
  2. Add Spring Security's DelegatingFilterProxy to the web deployment descriptor.
  3. Create an aplication-level Spring context containing Spring Security configuration..

Spring Security's DelegatingFilterProxy is essentially a J2EE Filter which nominally handles all requests and determines how to allow or reject access.






Spring's ContextLoaderListener is needed because there is now a parent Spring context which is inherited by the spring-mvc context of before. The contextConfigLocation parameter specifies the location of the new parent configuration file.


<!-- Enable Spring Security with HTTP basic authentication. -->
<http auto-config="true">
    <http-basic />
    <intercept-url pattern="/**" access="ROLE_USER" />
    <form-login />

<!-- An AuthenticationProvider with sample users and roles. -->
            <user name="jmcdoe" password="jmcdoe" authorities="ROLE_USER" />

This nearly minimal configuration sets up an in-memory repository of roles, and enforces access to every resource against this repository. Here, a form-based login page is provided by Spring.