(Recovered from my old Blog).
Getting Spring Security setup only involves a few steps, but it can be confusing to work out exactly what they are – especially since almost all documentation refers to Spring Security 2, and there are a couple of differences.
The first thing to do is to add the Spring Security dependencies to your Maven pom.xml. A good explanation of which ones are needed is located here. In summary though, you probably want the following Artifact ids (Group id is org.springframework.security):
(Note – be careful, for some reason the main Maven repository has a few spring-security-* artifacts under the Group id org.springframework – but they aren’t physically located there and you will get ‘Artifact Not Found’ errors).
After they are downloaded, you need to add the following to web.xml:
The extra context configuration puts all the security related information into a separate Spring xml for clarity (plus a different default namespace – we’ll see this in a minute).
The new filter does exactly as expected – intercepts calls to /* (sub-directories included) and applies the Spring Security rules (which we have yet to define).
As specified above, create the file /WEB-INF/applicationContext-security.xml. This file looks like a normal Spring config file, except instead of the default namespace being beans it is security – this means that all references to tags which are normally valid need to be prefixed with beans: (see below for an example).
Pay attention to this config – it is this file which is slightly different from Spring 2.
<?xml version="1.0" encoding="UTF-8"?>
<intercept-url pattern="/client/**" access="ROLE_USER" />
<intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<user name="ned" password="ned" authorities="ROLE_USER" />
Breaking this file down, the ‘key’ tag is http. The auto-config attribute tells Spring Security to add in all the ‘normal’ configuration properties. As you get more comfortable with Spring Security, you may want to override some of these defaults (e.g. the form to show that captures login information).
The user-service tag adds a single valid user, ned. In a more likely scenario, the user-service will be hooked up to a database to get a list of valid users – that’s an exercise for another day.
The intercept-url patterns are fairly self-explanatory, with one caveat: Spring Security resolves them top-to-bottom, and chooses the first one that matches. Therefore, make sure your more granular, specific patterns are at the top and a catch-all like “/**” goes at the bottom.
Set the above into your Spring application, then try and access your_site/client/whatever.html. All being well, you should be prompted with the default Spring Security login page. Put in the credentials you entered into the user-service and you’re all set. Congratulations, you just secured your website using Spring Security!