Spring Security
Make the following changes to the Spring and Hibernate application we created in the previous step:
1. Add the following dependencies:
-
org.springframework.security:spring-security-web
-
org.springframework.security:spring-security-config
2. Add the following to web.xml:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The DelegatingFilterProxy is the entry point of Spring Security, which utilizes a number of handler interceptors (Spring's equivalent of servlet filters) and method interceptors configured in applicationContext.xml to implement security. Note that the URL pattern /* ensures that all requests will pass through Spring Security.
3. Add the security namespace to applicationContext.xml so the beginning of the file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
And then add the following to applicationContext.xml:
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource" />
</security:authentication-provider>
</security:authentication-manager>
<security:http auto-config="true">
<security:intercept-url pattern="/users.html" access="ROLE_ADMIN" />
</security:http>
Authentication is done using the users and authorities table we created in the previous step. Here we simply let <jdbc-user-service> reference the data source and Spring Security will take care of the rest. The <http> element sets up a number of Spring Security filters for a web application environment, and <intercept-url> can be used to control access to certain URL patterns based on the roles of a user. And this is it. Your web application now have some basic security measures in place.
|