Spring Security 3.0

This article publishes the book excerpt from the book Spring Security 3.0.The following are the list of chapters in the book and brief description inside each chapters. If you are interested in receiving the future articles on book reviews and latest news on Java, please subscribe here.

Welcome to the world of Spring Security 3! I’m certainly pleased that you have acquired the first published book fully devoted to Spring Security, and i hope that it fulfills your every wish for a technical book on this fascinating subject. I’d like to use this introduction to set your expectations for the pages ahead, and give you some advice to help you along your way.

also read:

By the time you finish this book, you should feel comfortable with the architecture of Spring Security, the incorporation of Spring Security in a web-based application, and the integration of Spring Security with many types of external authentication and authorization systems.

The book is largely divided into two halves. The first half (Chapters 1-7) covers Spring Security as part of a web application from start to finish—very basic initial setup, all the way to advanced access control list security. The second half (Chapters 8-12) covers Spring Security as part of a larger software ecosystem, illustrating integration with common external systems such as OpenID, Microsoft Active Directory, and LDAP. The final chapter covers migration issues when moving from Spring Security 2 to Spring Security 3.

The book uses a simple Spring Web MVC based application to illustrate the concepts presented in the book. The application is intended to be very simple and straightforward, and purposely contains very little functionality—the goal of this application is to encourage you to focus on the Spring Security concepts, and not get tied up in the complexities of application development. You will have a much easier time following the book if you take the time to review the sample application source code, and try to follow along with the exercises. Some tips on getting started are in Chapter 1, Anatomy of an Unsafe Application and Appendix, Additional Reference Material.

What This Book Covers

Chapter 1, Anatomy of an Unsafe Application covers a hypothetical security audit of our e-commerce site, illustrating common issues that can be resolved through proper application of Spring Security. You will learn about some basic security terminology, and review some prerequisites for getting the sample application up and running.

Chapter 2, Getting Started with Spring Security reviews basic setup and configuration of form-based authentication with Spring Security, followed by a high-level overview of how Spring Security works from start to finish to secure web requests.

Chapter 3, Enhancing the User Experience illustrates additional user-facing functionality supported by Spring Security that can increase the usability of secured sites, including a remember me function, a styled login page, logout, and password change capability.

Chapter 4, Securing Credential Storage guides you through the key configuration steps required to secure your users’ information in a JDBC database, using Spring Security APIs. Important security concepts around safe password storage are also covered in this chapter.

Chapter 5, Fine-Grained Access Control covers in-page authorization checking (partial page rendering), and business-layer security using Spring Security’s method security capabilities.

Chapter 6, Advanced Configuration and Extension provides several hands-on walkthroughs of common customizations to Spring Security implementations, including custom servlet filters, custom authentication providers, and custom exception handling. Session fixation and concurrent session control are analyzed and appropriately applied to the site with required configuration steps reviewed. Finally, explicit bean-based configuration is clearly illustrated for all Spring Security functionality covered in the book.

Chapter 7, Access Control Lists teaches you the concepts and basic implementation of business object-level security using the Spring Security Access Control Lists module—a powerful module with very flexible applicability to challenging business security problems.

Chapter 8, Opening up to OpenID covers OpenID-enabled login and user information exchange, as well as a high-level overview of the logical flow of an OpenID-enabled system.

Chapter 9, LDAP Directory Services provides a guide to application integration with an LDAP directory server, including practical tips on different types of integrations with LDAP data.

Chapter 10, Single Sign On with Central Authentication Service shows how integration with Central Authentication Service (CAS) can provide single sign-on support to your Spring Security-enabled application.

Chapter 11, Client Certificate Authentication makes X.509 certificate-based authentication a clear alternative for certain business scenarios where managed certificates can add an additional layer of security to our application.

Chapter 12, Spring Security Extensions covers the Spring Security Kerberos extension project, which exposes a Kerberos integration layer for user authentication in our Spring Security application providing compatibility with a Unix Kerberos environment or Microsoft Active Directory.

Chapter 13, Migration to Spring Security 3 lays out the major differences between Spring Security 2 and Spring Security 3, including notable configuration changes, class and package migrations, and important new features. If you are familiar with Spring Security 2, we recommend that you read this chapter first, as it may make it easier to tie the examples back to code with which you are familiar.

Appendix, Additional Reference Material covers some reference material, which we feel is helpful (and largely undocumented) and too comprehensive to insert in the text of the chapters.

Securing Credential Storage

Up to this point, we’ve updated the JBCP Pets site with user-friendly functionality, including a custom login page, and change password and remember me features.

In this chapter, we’ll make a leap to a database-backed authentication store from the in-memory store we have used in the book until this point. We’ll explore the default expected Spring Security database schema, and will look into ways to extend JDBC implementation with customization.

During the course of this chapter, we’ll:

  • Understand how to configure Spring Security to utilize the services of a JDBC-accessible database to store and authenticate users
  • Learn how to configure a JDBC-compatible in-memory database using HSQLDB, for developer testing purposes
  • Work through the process of adapting Spring Security JDBC to an existing legacy schema
  • Examine two techniques for user and password management, both with out of the box and custom techniques
  • Examine different methods of configuring password encoding
  • Understand the password salting technique of providing additional security to stored passwords
  • Solve the problem of allowing user remember me tokens to persist even if the server restarts
  • Secure the application transport layer by understanding how to configure SSL/TLS encryption and port mapping

Database-backed authentication with Spring Security

An obvious issue with our more security-conscious implementation of JBCP Pets is that our in-memory storage of users and passwords is too short-lived to be user-friendly. As soon as the application is restarted, any new user registrations, password changes, or other activity will be lost. This isn’t acceptable, so the next logical implementation step when securing JBCP Pets will be to reconfigure Spring Security to utilize a relational database for user storage and authentication. The use of a JDBC-accessible relational database will allow user data to persist through application server restarts, and is more typical of real-world Spring Security use.

Configuring a database-resident authentication store

The first portion of this exercise involves setting up an instance of the Java-based relational database HyperSQL DB (or HSQL, for short), populated with the Spring Security default schema. We’ll configure HSQL to run in-memory using Spring 3′s embedded database configuration feature—a significantly simpler method of configuration than setting up the database by hand.

Keep in mind that in this example (and the remainder of the book), we’ll use HSQL, primarily, due to its ease of setup. We encourage you to tweak the configuration and use the database of your preference if you’re following along with the examples. As we didn’t want this portion of the book to focus on the complexities of database setup, we chose convenience over realism for the purposes of the exercises.

Creating the default Spring Security schema

We’ve supplied an SQL file, security-schema.sql, which will create all the tables required to implement Spring Security using HSQL. If you’re following along with your own database instance, you may have to adjust the schema definition syntax to fit your particular database. We’ll place this SQL file so that it’s on the classpath in WEB-INF/classes.

Configuring the HSQL embedded database

To configure the HSQL embedded database, we’ll modify the dogstore-security. xml file to both set up the database and run SQL to create the Spring Security table
structure. First, we’ll add a reference to the jdbc XML schema definition at the top of the file:


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:jdbc="http://www.springframework.org/schema/jdbc"
 xsi:schemaLocation="

http://www.springframework.org/schema/beans


http://www.springframework.org/schema/beans/spring-beans.xsd


http://www.springframework.org/schema/jdbc


http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd


http://www.springframework.org/schema/security


http://www.springframework.org/schema/security/

 spring-security3.0.xsd"
 >
 

Next, we’ll declare the element, along with a reference to the SQL script:

	<jdbc:embedded-database id="dataSource" type="HSQL">
		<jdbc:script location="classpath:security-schema.sql"/>
	</jdbc:embedded-database>

If you start the server at this point, you should be able to see the initialization of the HSQL database in the logs. Remember that the declaration creates this database only in the memory, so you won’t see anything on disk, and you won’t be able to use standard tools to query it.

Configuring JdbcDaoImpl authentication store

We’ll modify the dogstore-security.xml file to declare that we’re using a JDBC UserDetailsService implementation, instead of the Spring Security in-memory UserDetailsService that we configured in Chapter 2, Getting Started with Spring Security and Chapter 3, Enhancing the User Experience. This is done with a simple change to the declaration:

	<authentication-manager alias="authenticationManager">
		<authentication-provider>
			<b><jdbc-user-service data-source-ref="dataSource"/></b>
		</authentication-provider>
	</authentication-manager>

The data-source-ref refers to the bean we declared using the shortcut declaration in the previous step.

Adding user definitions to the schema

Finally, we’ll create another SQL file that will get executed when the in-memory database is created. This SQL file will contain information about our default users, admin and guest, with the same GrantedAuthority settings that we’ve used in prior chapters. We’ll call this SQL file test-data.sql, and we’ll put it alongside security-schema.sql in WEB-INF/classes:

	insert into users(username, password, enabled) values
		('admin','admin',true);
	insert into authorities(username,authority) values
		('admin','ROLE_USER');
	insert into authorities(username,authority) values
		('admin','ROLE_ADMIN');
	insert into users(username, password, enabled) values
		('guest','guest',true);
	insert into authorities(username,authority) values
		('guest','ROLE_USER');
	commit;

Next, we’ll need to add this SQL file to the embedded database configuration so that it is loaded at startup:

	<jdbc:embedded-database id="dataSource" type="HSQL">
		<jdbc:script location="classpath:security-schema.sql"/>
		<b><jdbc:script location="classpath:test-data.sql"/></b>
	</jdbc:embedded-database>

After the SQL is added to the embedded database configuration, we should be able to start the application and log in. Spring Security is now looking at the database for authentication and GrantedAuthority information!

How database-backed authentication works

You may recall from our examination of the authentication process in Chapter 2 that the AuthenticationManager delegates to AuthenticationProvider to validate the credentials of the principal and ensure that it should be able to access the system at all. The AuthenticationProvider that we have been using in Chapters 2 and 3 was the DaoAuthenticationProvider. This provider delegates to a UserDetailsService implementation to retrieve and validate the information about the principal from the credential store. We can see this in the diagram from Chapter 2:

1As you may anticipate, the only meaningful difference between our configuration of a database-backed authentication store and the in-memory store is the implementation of the UserDetailsService. The o.s.s.core.userdetails. jdbc.JdbcDaoImpl class provides an implementation of a UserDetailsService. Instead of looking at an in-memory store (populated from the Spring Security XML configuration), the JdbcDaoImpl looks up users in a database.

2You may note that we didn’t reference the implementation class at all. This is because the declaration in the updated Spring Security
configuration will automatically configure the JdbcDaoImpl and wire it up to the AuthenticationProvider. Later in this chapter, we’ll see how to configure Spring Security to use our own implementation of JdbcDaoImpl, which continues to support the change password feature that we added to our custom InMemoryDaoImpl in Chapter 3. Let’s examine the configuration required to implement our own JdbcDaoImpl subclass that supports the change password function.

Implementing a custom JDBC UserDetailsService

As we did in one of the exercises in the previous chapter, we’ll take the baseline JdbcDaoImpl as our starting point, and extend it to support a change password function.

Creating a custom JDBC UserDetailsService class

Create the following class in the com.packtpub.springsecurity.security package:

	public class CustomJdbcDaoImpl extends JdbcDaoImpl implements
	IChangePassword {
		public void changePassword(String username, String password) {
			getJdbcTemplate()
			update("UPDATE USERS SET PASSWORD = ? WHERE USERNAME = ?",
				password, username);
		}
	}

You can see that this simple class extends the default JdbcDaoImpl with a function to update the password in the database to the new password that the user ostensibly requested. We use standard Spring JDBC functionality to do this.

Adding a Spring Bean declaration for the custom UserDetailsService

Add the following Spring Bean declaration to the dogstore-base.xml Spring configuration file:

	<bean id="jdbcUserService"
		class="com.packtpub.springsecurity.security.CustomJdbcDaoImpl">
		<property name="dataSource" ref="dataSource"/>
	</bean>

Again, the dataSource Bean reference here resolves to the declaration we made to set up the HSQL in-memory database. You’ll observe that the custom UserDetailsService implementation allows us to tweak the interaction with the database significantly. We’ll use this capability to expand the baseline functionality of the UserDetailsService in later examples. This type of customization is very common in complex applications of Spring Security.

Out of the box JDBC-based user management

As our simple extension to JdbcDaoImpl illustrated, one might extend the class, while retaining the baseline functionality at the same time. But what if we wanted to implement more advanced features, such as user registration (a must for an online store!) and user management features, allowing site administrators to create users, update passwords, and so on?

Although these types of functions are relatively easy to write with additional JDBC statements, Spring Security actually provides out of the box functionality to support many common Create, Read, Update, and Delete (CRUD) operations on users in JDBC databases. This can be convenient for simple systems, and a good base to build on for any custom requirements that a user may have.

The implementation class o.s.s.provisioning.JdbcUserDetailsManager conveniently extends JdbcDaoImpl for us, and provides a number of
helpful user-related methods, declared as part of the o.s.s.provisioning. UserDetailsManager interface:

3As you can see, the changePassword method on JdbcUserDetailsManager precisely fits a gap in the functionality of our CustomJdbcDaoImpl class – it will verify the user’s existing password when changing it. Let’s review the configuration steps required to replace our CustomJdbcDaoImpl with the JdbcUserDetailsManager.

First, we’ll have to make need to declare the JdbcUserDetailsManager bean in dogstore-base.xml:

	<bean id="jdbcUserService"
			class="org.springframework.security
				.provisioning.JdbcUserDetailsManager">
		<property name="dataSource" ref="dataSource"/>
		<property name="authenticationManager"
			ref="authenticationManager"/>
	</bean>

The reference to AuthenticationManager matches the alias we’ve previously declared in the element in dogstore-security.xml.
Don’t forget to comment out the declaration of the CustomJdbcDaoImpl bean—we will (temporarily) not be using it.

Next, we’ll have to make some minor adjustments to the changePassword.jsp page:

	<h2>Change Password</h2>
		<form method="post">
			<b><label for="oldpassword">Old Password</label>:
			<input id="oldpassword" name="oldpassword"
				size="20" maxlength="50" type="password"/>
			<br /></b>
			<label for="password">New Password</label>:
			<input id="password" name="password" size="20"
				maxlength="50" type="password"/>
			<br />

Finally, we’ll have to make some minor adjustments to AccountController. Replace the @Autowired reference to the IChangePassword implementation with:

	@Autowired
	private UserDetailsManager userDetailsManager;

The submitChangePasswordPage also becomes much simpler, as we are relying on information about the current authenticated principal which the
JdbcUserDetailsManager determines on our behalf:

	public String submitChangePasswordPage(@RequestParam("oldpassword")
			String oldPassword,
		@RequestParam("password") String newPassword) {
			userDetailsManager.changePassword(oldPassword, newPassword);
			SecurityContextHolder.clearContext();
			return "redirect:home.do";
		}

Once these changes are complete, you can restart the web application and try out the new change password functionality!

Notice what happens when you don’t supply the correct password. Why do you think this happens? Try to think through how you’d adjust the behavior to make it more user friendly.

Although we won’t demonstrate all of the functionality supported by JdbcUserDetailsManager, we can see that it would be very easy to wire simple JSP pages (properly secured with authorization, of course!) to allow administrators to manage users of the site—essential for a production website!

Advanced configuration of JdbcDaoImpl

JdbcDaoImpl has a number of configuration options that allow for adapting its use to an existing schema, or for more sophisticated adjustment of its existing capabilities. In many cases, it’s possible to adapt the configuration of the out of the box JDBC UserDetailsService without having to write your own code.

One important feature is the ability to add a level of indirection between users and GrantedAuthority declarations by grouping GrantedAuthority into logical sets
called groups. Users are then assigned one or more groups, whose membership confers a set of GrantedAuthority declarations.

4As you see in the diagram, this indirection allows the assignment of the same set of roles to multiple users, by simply assigning any new users to existing groups. Contrast this with the behavior we’ve seen this far, where we assigned GrantedAuthority directly to individual users.

This bundling of common sets of authorities can be helpful in the following scenarios:

  • You need to segregate users into communities, with some overlapping roles between groups.
  • You want to globally change authorization for a class of user. For example, if you have a “supplier” group, you might want to enable or disable their access to particular portions of the application.
  • You have a large number of users, and you don’t need a user-level authority configuration.

Unless your application has a very small user base, there is a very high likelihood that you’ll be using group-based access control. The management ease and fl exibility of this rights management approach far outweighs the slightly greater complexity. This indirect technique of aggregating user privileges by group is commonly referred to as Group-Based Access Control (GBAC).

Group-based access control is an approach common to almost every
secured operating system or software package in the market. Microsoft
Active Directory (AD) is one of the most visible implementations of
large-scale GBAC, due to its design of slotting AD users into groups and
assignment of privileges to those groups. Management of privileges in
large AD-based organizations is made exponentially simpler through the
use of GBAC.
Try to think of the security models of the software you use—how are
users, groups, and privileges managed? What are the pros and cons of the
way the security model is written?

Let’s add a level of abstraction to JBCP Pets and apply the concept of group-based authorization to the site.

Configuring group-based authorization

We’ll add two groups to the website—regular users, which we’ll call “Users”, and administrative users, which we’ll call “Administrators”. Our existing guest and admin user accounts will be dropped into the appropriate groups through modifications to our SQL script that we use to set up the database.

Configuring JdbcDaoImpl to use groups

First, we must set properties on our JdbcDaoImpl custom subclass to enable the use of groups, and disable the use of direct authority granting to users. Add the following to the bean definition in dogstore-base.xml:

	<bean id="jdbcUserService"
		class="com.packtpub.springsecurity.security.CustomJdbcDaoImpl">
		<property name="dataSource" ref="dataSource"/>
		<b><property name="enableGroups" value="true"/>
		<property name="enableAuthorities" value="false"/></b>
	</bean>

Note that if you are following along and still have the code and configuration changes in place to utilize the JdbcUserManager, please revert them as we’ll be using the CustomJdbcDaoImpl for the remainder of this chapter.

Modifying the initial load SQL script

We’ll simply modify the SQL that we use to populate the database to:

  • Define our groups
  • Assign GrantedAuthority specifications to groups
  • Assign users to groups

For simplicity, we’ll create a new SQL script called test-users-groups-data.sql. We’ll add the groups first:

	insert into groups(group_name) values ('Users');
	insert into groups(group_name) values ('Administrators');

Next, assign roles to groups:

	insert into group_authorities(group_id, authority) select id,'ROLE_
	USER' from groups where group_name='Users';
	insert into group_authorities(group_id, authority) select id,'ROLE_
	USER' from groups where group_name='Administrators';
	insert into group_authorities(group_id, authority) select id,'ROLE_
	ADMIN' from groups where group_name='Administrators';

Next, create the users:

	insert into users(username, password, enabled) values
	('admin','admin',true);
	insert into users(username, password, enabled) values
	('guest','guest',true);

Finally, assign users to groups:

	insert into group_members(group_id, username) select id,'guest' from
	groups where group_name='Users';
	insert into group_members(group_id, username) select id,'admin' from
	groups where group_name='Administrators';

Modifying the embedded database creation declaration

We’ll need to update the creation of our embedded HSQL database to reference this script in lieu of the existing test-data.sql script:

	<jdbc:embedded-database id="dataSource" type="HSQL">
		<jdbc:script location="classpath:security-schema.sql"/>
		<b><jdbc:script location="classpath:test-users-groups-data.sql"/></b>
	</jdbc:embedded-database>

Note that the security-schema.sql already contains declarations for the tables required to support the group structure, so we don’t need to modify that script.

At this point, you should be able to start the JBCP Pets site again and it will behave just as before; however, the additional layer of abstraction between users and privileges will enable us to develop some sophisticated user management functionality in later exercises with a fraction of effort.

Let’s step away from the JBCP Pets scenario for a moment and cover one more important bit of configuration while we’re in this area.

Using a legacy or custom schema with database-resident authentication

It’s common for new users of Spring Security to begin their experience by adapting the JDBC user, group, or role mapping to an existing schema. Even though a legacy database doesn’t conform to the expected Spring Security schema, we can still configure the JdbcDaoImpl to map to it. Imagine we have an existing legacy database schema similar to the following figure, onto which we are going to implement Spring Security.

5We can easily change the configuration of JdbcDaoImpl to utilize this schema and override the Spring Security expected table definitions and columns that we’re using for JBCP Pets.

Determining the correct JDBC SQL queries

JdbcDaoImpl has three SQL queries which have a well-defined parameter and set of returned columns. We must determine the SQL that we’ll assign to each of these queries, based on its intended functionality. Each SQL query used by the JdbcDaoImpl takes the username presented at login as its one and only parameter.

67Be aware that in some cases, the return columns are not used by the default JdbcDaoImpl implementation, but they must be returned anyway. Spend some time now trying to write these queries for the database diagram on the previous page before moving on to the next step.

Configuring the JdbcDaoImpl to use custom SQL queries

In order to use the custom SQL queries for our non-standard schema, we’ll simply configure the JdbcDaoImpl properties in the Spring Bean configuration file. Note that in order to configure the JDBC queries on JdbcDaoImpl, you cannot use the declaration. You must explicitly instantiate the bean, as we’ve done with our custom JdbcDaoImpl.

	<bean id="jdbcUserService"
		class="com.packtpub.springsecurity.security.CustomJdbcDaoImpl">
		<property name="dataSource" ref="dataSource"/>
		<property name="enableGroups" value="true"/>
		<property name="enableAuthorities" value="false"/>
		<b><property name="usersByUsernameQuery">
			<value>SELECT LOGIN, PASSWORD,
				1 FROM USER_INFO WHERE LOGIN = ?
			</value>
		</property>
		<property name="groupAuthoritiesByUsernameQuery">
			<value>SELECT G.GROUP_ID, G.GROUP_NAME, P.NAME
				FROM USER_INFO U
				JOIN USER_GROUP UG on U.USER_INFO_ID = UG.USER_INFO_ID
				JOIN GROUP G ON UG.GROUP_ID = G.GROUP_ID
				JOIN GROUP_PERMISSION GP ON G.GROUP_ID = GP.GROUP_ID
				JOIN PERMISSION P ON GP.PERMISSION_ID = P.PERMISSION_ID
				WHERE U.LOGIN = ?
			</value>
		</property></b>
	</bean>

This is the only configuration required to use Spring Security to read settings from an existing, non-default schema! Keep in mind that utilization of an existing schema commonly requires extension of the JdbcDaoImpl to support changing of passwords, renaming of user accounts, and other user-management functions.

If you are using the JdbcUserDetailsManager to perform user management tasks, be aware that (as of this writing) only some of the over twenty SQL queries utilized by the class are accessible through configuration. Please refer to the Javadoc or source code to review the defaults for the queries used by the JdbcUserDetailsManager.

Configuring secure passwords

We recall from the security audit in Chapter 1, Anatomy of an Unsafe Application that the security of passwords stored in cleartext was a top priority of the auditors. In fact, in any secured system, password security is a critical aspect of trust and authoritativeness of an authenticated principal. Designers of a fully secured system must ensure that passwords are stored in a way in which malicious users would have an impractically difficult time compromising them.

The following general rules should be applied to passwords stored in a database:

  • Passwords must not be stored in cleartext (plain text)
  • Passwords supplied by the user must be compared to recorded passwords in the database
  • A user’s password should not be supplied to the user upon demand (even if the user forgets it)

For the purposes of most applications, the best fit for these requirements involves one-way encoding or encryption of passwords as well as some type of randomization of the encrypted passwords. One-way encoding provides the security and uniqueness properties that are important to properly authenticate users with the added bonus that once encrypted, the password cannot be decrypted.

In most secure application designs, it is neither required nor desirable to ever retrieve the user’s actual password upon request, as providing the user’s password to them without proper additional credentials could present a major security risk. Most applications instead provide the user the ability to reset their password, either by presenting additional credentials (such as their social security number, date of birth, tax ID, or other personal information), or through an email-based system.

Storing other types of sensitive information
Many of the guidelines listed that apply to passwords apply equally to
other types of sensitive information, including social security numbers
and credit card information (although, depending on the application,
some of these may require the ability to decrypt).

It’s quite common for databases storing this type of information to represent it in multiple ways, for example, a customer’s full 16-digit credit card number would be stored in a highly encrypted form, but the last four digits might be stored in cleartext (for reference, think of any internet commerce site that displays XXXX XXXX XXXX 1234 to help you identify your stored credit cards).

You may already be thinking ahead and wondering, given our (admittedly unrealistic) approach of using SQL to populate our HSQL database with users, how do we encode the passwords? HSQL, or most other databases for that matter, don’t offer encryption methods as built-in database functions.

Typically, the bootstrap process (populating a system with initial users and data) is handled through some combination of SQL loads and Java code. Depending on the complexity of your application, this process can get very complicated.

For the JBCP Pets application, we’ll retain the embedded-database declaration and the corresponding SQL, and then add a small bit of Java to fire after the initial load to encrypt all the passwords in the database. For password encryption to work properly, two actors must use password encryption in synchronization ensuring that the passwords are treated and validated consistently.

8Password encryption in Spring Security is encapsulated and defined by implementations of the o.s.s.authentication.encoding.PasswordEncoder interface. Simple configuration of a password encoder is possible through the declaration within the
element as follows:

	<authentication-manager alias="authenticationManager">
		<authentication-provider user-service-ref="jdbcUserService">
			<b><password-encoder hash="sha"/></b>
		</authentication-provider>
	</authentication-manager>

You’ll be happy to learn that Spring Security ships with a number of implementations of PasswordEncoder, which are applicable for different needs and security requirements. The implementation used can be specified using the hash attribute of the declaration.

The following table provides a list of the out of the box implementation classes and their benefits. Note that all implementations reside in the o.s.s.authentication. encoding package.

9As with many other areas of Spring Security, it’s also possible to reference a bean definition implementing PasswordEncoder to provide more precise configuration and allow the PasswordEncoder to be wired into other beans through dependency injection. For JBCP Pets, we’ll need to use this bean reference method in order to encode the bootstrapped user data.

Let’s walk through the process of configuring basic password encoding for the JBCP Pets application.

Configuring password encoding

Configuring basic password encoding involves two pieces—encrypting the passwords we load into the database after the SQL script executes, and ensuring that the DaoAuthenticationProvider is configured to work with a PasswordEncoder.

Configuring the PasswordEncoder

First, we’ll declare an instance of a PasswordEncoder as a normal Spring bean:

	<bean class="org.springframework.security.authentication.
		encoding.ShaPasswordEncoder" id="passwordEncoder"/>

You’ll note that we’re using the SHA-1 PasswordEncoder implementation. This is an efficient one-way encryption algorithm, commonly used for password storage.

Configuring the AuthenticationProvider

We’ll need to configure the DaoAuthenticationProvider to have a reference to the PasswordEncoder, so that it can encode and compare the presented password during user login. Simply add a declaration and refer to the bean ID we defined in the previous step:

	<authentication-manager alias="authenticationManager">
		<authentication-provider user-service-ref="jdbcUserService">
			<b><password-encoder ref="passwordEncoder"/></b>
		</authentication-provider>
	</authentication-manager>

Try to start the application at this point, and then try to log in. You’ll notice that what were previously valid login credentials are now being rejected. This is because the passwords stored in the database (loaded with the bootstrap test-users-groupsdata. sql script) are not stored in an encrypted form that matches the password encoder. We’ll need to post-process the bootstrap data with some simple Java code.

Writing the database bootstrap password encoder

The approach we’ll take for encoding the passwords loaded via SQL is to have a Spring bean that executes an init method after the embedded-database bean is
instantiated. The code for this bean, com.packtpub.springsecurity.security. DatabasePasswordSecurerBean, is fairly simple.

	public class DatabasePasswordSecurerBean extends JdbcDaoSupport {
		@Autowired
		private PasswordEncoder passwordEncoder;
		public void secureDatabase() {
			getJdbcTemplate().query("select username, password from users",
				new RowCallbackHandler(){
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				String username = rs.getString(1);
				String password = rs.getString(2);
				String encodedPassword = passwordEncoder.encodePassword(password, null);
				getJdbcTemplate().update("update users set password = ?
						where username = ?", encodedPassword,username);
					logger.debug("Updating password for username:
						"+username+" to: "+encodedPassword);
				}
			});
		}
	}

The code uses the Spring JdbcTemplate functionality to loop through all the users in the database and encode the password using the injected PasswordEncoder reference. Each password is updated individually.

Configuring the bootstrap password encoder

We need to configure the Spring bean declaration such that the bean is initialized upon start of the web application and after the bean. Spring bean dependency tracking ensures that the DatabasePasswordSecurerBean executes at the proper time:

	<bean class="com.packtpub.springsecurity.security.
			DatabasePasswordSecurerBean"
			init-method="secureDatabase" depends-on="dataSource">
		<property name="dataSource" ref="dataSource"/>
	</bean>

If you start the JBCP Pets application at this point, you’ll see that the passwords in the database are encoded, and login now functions properly.

Would you like some salt with that password?

If the security auditor were to examine the encoded passwords in the database, he’d find something that would still make him concerned about the website’s security. Let’s examine what the stored username and password values are for our admin and guest users:

10This looks very secure—the encrypted passwords obviously bear no resemblance to the original passwords. What could the auditor be concerned about? What if we add a new user who happens to have the same password as our admin user?

11Now, note that the encrypted password of the fakeadmin user is exactly the same as the real admin user! Thus a hacker who had somehow gained the ability to read the encrypted passwords in the database could compare their known password’s encrypted representation with the unknown one for the admin account, and see they are the same! If the hacker had access to an automated tool to perform this analysis, they could likely compromise the administrator’s account within a matter of hours.

Having personally worked with a database where passwords were
encrypted in exactly this way, my engineering team and idecided to
run a little experiment and see what the SHA-1 encrypted value of the
plaintext password password was. We then took the encrypted form of
the word password and ran a database query to see how many users
in the database had this highly insecure password. To our surprise and
dismay, we found many, including a VP of the organization. Each user
got a nice follow-up email reminder about the benefits of choosing a
hard to guess password, and development quickly got to work on a more
secure password encryption mechanism!

Recall our mention in Chapter 3 of rainbow table techniques that malicious users can use to determine user passwords if they have access to the database. These (and other) hacking techniques take advantage of the fact that hash algorithms are deterministic—the same input always leads to the same output, and as such, if an attacker tries enough inputs, they may happen to match an unknown output to the result of a known input.

One common, and effective, method of adding another layer of security to encrypted passwords is to incorporate a salt. A salt is a second plaintext component which is concatenated with the plaintext password prior to encryption in order to ensure that two factors must be used to generate (and thus compare) encrypted password values. Properly selected salts can guarantee that no two passwords will ever have the same encrypted value, thus preventing the scenario that concerned our auditor, and avoiding many common types of brute force password cracking techniques.

Best practice salts generally fall into one of two categories:

  • They are algorithmically generated from some piece of data associated with the user—for example, the timestamp that the user was created
  • They are randomly generated, and stored in some form (plaintext or two-way encrypted) along with the user’s password record

For example, the following diagram illustrates the simple case where the salt is the same as the user’s login name:

12Remember that because the salt is added to the plaintext password, the salt can’t be one-way encrypted—the application needs to be able to look up or derive the appropriate salt value for a given user’s record in order to authenticate the user!

Spring Security provides us with an interface, o.s.s.authentication.dao. SaltSource, which defines a method to return a salt value from the UserDetails object, along with two out of the box implementations:

  • SystemWideSaltSource defines a single, static salt used for every password. This is not significantly more secure than an unsalted password.
  • ReflectionSaltSource uses a bean property of the UserDetails object to get the salt value for that user’s password.

Since salt values should be derivable from, or stored with each user record, ReflectionSaltSource is the out of the box implementation that most implementers typically use.

Configuring a salted password

As with configuring basic password encryption in the previous exercise, adding elements to support a salted password requires changes in both the bootstrap code and the DaoAuthenticationProvider We can examine how the workfl ow of salted passwords changes bootstrap and authentication by revising the following diagram occurred earlier in the book:

13Let’s add a level of password security by configuring the ReflectionSaltSource to salt our passwords!

Declaring the SaltSource Spring bean

In dogstore-base.xml, add a bean declaration for the SaltSource implementation we’re using:

	<bean class="org.springframework.security.authentication.
			dao.ReflectionSaltSource" id="saltSource">
		<property name="userPropertyToUse" value="username"/>
	</bean>

We’re configuring the salt source to use the username property, but this is a short-term implementation that we’ll correct in a later exercise. Can you think why this might not be a good salt value?

Wiring the PasswordEncoder to the SaltSource

We’ll need to hook up the SaltSource to the PasswordEncoder, so that the credentials the user presents upon login can be appropriately salted, prior to
comparison with stored values. This is done by adding a new declaration in dogstore-security.xml:

	<authentication-manager alias="authenticationManager">
		<authentication-provider user-service-ref="jdbcUserService">
			<password-encoder ref="passwordEncoder">
				<b><salt-source ref="saltSource"/></b>
			</password-encoder>
		</authentication-provider>
	</authentication-manager>

You’ll note that if you start up the application at this point, you won’t be able to log in. Just as in the previous exercise, the bootstrap database password encoder bean needs to be modified to include the SaltSource.

Augmenting DatabasePasswordSecurerBean

We’ll add a bean reference to the DatabasePasswordSecurerBean, as well as a reference to the UserDetailsService so that we can get the appropriate password
salt for the user:

	public class DatabasePasswordSecurerBean extends JdbcDaoSupport {
		@Autowired
		private PasswordEncoder passwordEncoder;
		<b>@Autowired
		private SaltSource saltSource;
		@Autowired
		private UserDetailsService userDetailsService;</b>
		public void secureDatabase() {
			getJdbcTemplate().query("select username, password from users",
			new RowCallbackHandler(){
				@Override
				public void processRow(ResultSet rs) throws SQLException {
					String username = rs.getString(1);
					String password = rs.getString(2);
					<b>UserDetails user = userDetailsService.loadUserByUsername(username);
					String encodedPassword = passwordEncoder.encodePassword(password,
						saltSource.getSalt(user));</b>
					getJdbcTemplate().update("update users set password = ?
						where username = ?",
						encodedPassword,
						username);
					logger.debug("Updating password for username:
						"+username+" to: "+encodedPassword);
				}
			});
		}
	}

Recall that the SaltSource relies on a UserDetails object to generate the salt value. At this point, as we don’t have the database row mapped to a UserDetails object, we’ll have to make a request to the UserDetailsService (our CustomJdbcDaoImpl) to look up the UserDetails based on the username from the SQL query response.

At this point, we should be able to start the application and properly log into the system. If you try adding a new user with the same password (for example, admin) to the bootstrap SQL script, you’ll note that the password generated for the user is different, because we’re salting the passwords with the username. This makes the passwords much more secure in the unlikely event that a malicious user is able to read the passwords from the database. However, you may have some ideas as to why using the username isn’t the most secure possible salt—we’ll explore this in later exercise.

Enhancing the change password functionality

One important change that we’ll need to make is to update the change Password functionality to refer to the password encoder implementation as well. This is as
simple as adding appropriate bean references to the CustomJdbcDaoImpl class, and minor code changes in the changePassword method:

	public class CustomJdbcDaoImpl extends JdbcDaoImpl {
		<b>@Autowired
		private PasswordEncoder passwordEncoder;
		@Autowired
		private SaltSource saltSource;</b>
		public void changePassword(String username, String password) {
			<b>UserDetails user = loadUserByUsername(username);
			String encodedPassword = passwordEncoder.encodePassword
				(password, saltSource.getSalt(user));</b>
				getJdbcTemplate().update(
					"UPDATE USERS SET PASSWORD = ? WHERE USERNAME = ?",
					encodedPassword, username);
		}

The use of the PasswordEncoder and SaltSource here will ensure that the user’s password is properly salted when changed. Curiously, use of a PasswordEncoder and SaltSource is not supported by the JdbcUserDetailsManager, so if you are using JdbcUserDetailsManager as a baseline for customization, you will need to override quite a bit of code.

Configuring a custom salt source

As mentioned when we first configured password salting, username is a feasible, but not extremely desirable, choice for a password salt. The reason for this is that username is a salt that is under direct control of the user. If users are provided with the ability to change their username, it would be possible for malicious users to continuously change their user names—thus re-salting their passwords—and possibly determine how to construct a falsely encrypted password.

More secure still would be to have a property of the UserDetails which is chosen by the system, and never visible to, or modifiable by the user. We’ll add a property to the UserDetails object that is populated at random when a user is created. This property will become the user’s salt.

Extending the database schema

We’ll need to ensure that the salt is stored in the database along with the user record, so we’ll add a column to the default Spring Security database schema, defined in security-schema.sql:

	create table users(
		username varchar_ignorecase(50) not null primary key,
		password varchar_ignorecase(50) not null,
		<b>enabled boolean not null,
		salt varchar_ignorecase(25) not null</b>
	);

Next, add the bootstrap salt values to the test-users-groups-data.sql script:

	insert into users(username, password, enabled, salt) values ('admin','
		admin',true,CAST(RAND()*1000000000 AS varchar));
	insert into users(username, password, enabled, salt) values ('guest','
		guest',true,CAST(RAND()*1000000000 AS varchar));

Remember, we’re replacing the insert statements that are already there with these new ones. Note that we’ve chosen salt values based on random number generation—any pseudo-random salt selection of your choice can be just as effective.

Tweaking configuration of the CustomJdbcDaoImplUserDetails service

Following similar steps as the custom schema exercise earlier in this chapter, we’ll add a configuration change to the query used to retrieve users from the database in order to pick up the additional ‘salt’ column. We’ll modify the CustomJdbcDaoImpl bean definition in dogstore-security.xml:

	<beans:bean id="jdbcUserService"
		class="com.packtpub.springsecurity.security.CustomJdbcDaoImpl">
		<beans:property name="dataSource" ref="dataSource"/>
		<beans:property name="enableGroups" value="true"/>
		<beans:property name="enableAuthorities" value="false"/>
		<b><beans:property name="usersByUsernameQuery">
			<beans:value>select username,password,enabled,
				salt from users where username = ?
			</beans:value>
		</beans:property></b>
	</beans:bean>

Overriding the baseline UserDetails implementation

We’ll need a UserDetails implementation that tracks the salt value stored with the user record in the database. Simply overriding the Spring standard User class is sufficient for our purposes. Remember to add a getter and setter for the salt, so that the ReflectionSaltSource password salter can find the right property.

	package com.packtpub.springsecurity.security;
	// imports
	public class SaltedUser extends User {
		private String salt;
		public SaltedUser(String username, String password,
			boolean enabled,
			boolean accountNonExpired, boolean credentialsNonExpired,
			boolean accountNonLocked, List<GrantedAuthority>
			authorities, String salt) {
				super(username, password, enabled,
				accountNonExpired, credentialsNonExpired,
				accountNonLocked, authorities);
				this.salt = salt;
			}
			public String getSalt() {
				return salt;
			}
			public void setSalt(String salt) {
				this.salt = salt;
			}
		}

Even though we are extending the UserDetails to capture a salt field, the process would be the same if we wanted to store additional information about the user from a backing store. Extension of the UserDetails object is commonly done in conjunction with the implementation of a custom AuthenticationProvider. We’ll see an example of this in Chapter 6, Advanced Configuration and Extension.

Extending the functionality of CustomJdbcDaoImpl

We need to override the methods of JdbcDaoImpl, responsible for instantiating the UserDetails implementation that sets the default values for User. This occurs while loading the User from the database, and then copying the User into the instance that actually gets returned from the UserDetailsService:

	public class CustomJdbcDaoImpl extends JdbcDaoImpl {
		public void changePassword(String username, String password) {
			getJdbcTemplate().update(
				"UPDATE USERS SET PASSWORD = ? WHERE USERNAME = ?"
				password, username);
		}
		@Override
		protected UserDetails createUserDetails(String username,
			UserDetails userFromUserQuery,
			List<GrantedAuthority> combinedAuthorities) {
				String returnUsername = userFromUserQuery.getUsername();
				if (!isUsernameBasedPrimaryKey()) {
					returnUsername = username;
				}
				return new SaltedUser(returnUsername,
				userFromUserQuery.getPassword(),userFromUserQuery.isEnabled(),
				true, true, true, combinedAuthorities,
				((SaltedUser) userFromUserQuery).getSalt());
			}
			@Override
			protected List<UserDetails> loadUsersByUsername(String username) {
				return getJdbcTemplate().
				query(getUsersByUsernameQuery(),
				new String[] {username},
				new RowMapper«UserDetails>() {
					public UserDetails mapRow(ResultSet rs, int rowNum)
					throws SQLException {
						String username = rs.getString(1);
						String password = rs.getString(2);
						boolean enabled = rs.getBoolean(3);
						String salt = rs.getString(4);
						return new SaltedUser(username, password,
						enabled, true, true, true,
						AuthorityUtils.NO_AUTHORITIES, salt);
					}
				});
			}
	}

The methods createUserDetails and loadUsersByUsername are adapted from the superclass methods—the changes from the superclass methods are highlighted in the code listing. With these changes, you should be able to restart the application and have extra secure, randomly salted passwords. You may wish to add logging, and experiment, to see how the encrypted values change on every run of the application, as the bootstrap users are loaded.

Keep in mind that although this example illustrated the addition of a simple field to the UserDetails implementation, this approach can be used as a baseline to a highly customized UserDetails object which fits the business needs of your application. For the purposes of JBCP Pets, the auditors are now sufficiently happy with the security of passwords in the database—a job well done!

Moving remember me to the database

Something that you may have noticed by now, with our remember me implementation, is that it works very well until the application server is restarted, at which point the user’s session is forgotten. This could be inconvenient for our users, who shouldn’t have to pay attention to the maintenance and ups and downs of JBCP Pets.

Fortunately, Spring Security provides the capability to persist rememberme tokens any store implementing the o.s.s.web.authentication.rememberme.
PersistentTokenRepository interface, and ships with a JDBC implementation of this interface.

Configuring database-resident remember me tokens

Modifying our remember me configuration at this point to persist to the database is surprisingly trivial. The Spring Security configuration parser will recognize a new data-source-ref attribute on the declaration and simply switch implementation classes for RememberMeServices. Let’s review the steps required to accomplish this now.

Adding SQL to create the remember me schema

We’ll place the SQL file containing the expected schema definition on the classpath in WEB-INF/classes, alongside the other bootstrap SQL scripts we’ve been working with. Let’s call this SQL script remember-me-schema.sql:

	create table persistent_logins (
		username varchar_ignorecase(50) not null,
		series varchar(64) primary key,
		token varchar(64) not null,
		last_used timestamp not null);

Adding new SQL script to the embedded database declaration

Next, add a reference to the new SQL script that we created in the declaration in dogstore-security.xml:

	<jdbc:embedded-database id="dataSource" type="HSQL">
		<jdbc:script location="classpath:security-schema.sql"/>
		<jdbc:script location="classpath:remember-me-schema.sql"/>
		<jdbc:script location="classpath:test-users-groups-data.sql"/>
	</jdbc:embedded-database>

Configuring remember me services to persist to the database

Finally, we’ll need to make some brief configuration changes to the declaration to point it to the data source we’re using:

	<http auto-config="true" use-expressions="true"
		access-decision-manager-ref="affirmativeBased">
		<intercept-url pattern="/login.do" access="permitAll"/>
		<intercept-url pattern="/account/*.do"
			access="hasRole('ROLE_USER') and fullyAuthenticated"/>
		<intercept-url pattern="/*" access="hasRole('ROLE_USER')"/>
		<form-login login-page="/login.do" />
		<remember-me key="jbcpPetStore" token-validity-seconds="3600"
			data-source-ref="dataSource"/>
		<logout invalidate-session="true" logout-success-url=""
			logout-url="/logout"/>
	</http>

That’s all we need. Now, if we restart the application, it will no longer forget users who previously had a valid remember me cookie set.

Are database-backed persistent tokens more secure?

You may recall that the TokenBasedRememberMeServices we implemented in Chapter 3 use MD5 hashing across a series of user-related data to encode the cookie securely, in a way that would be hard (but not impossible) to tamper with. The o.s.s.web. authentication.rememberme.PersistentTokenBasedRememberMeServices class implements handling of persistent tokens and handles token security with a validation method, which handles potential tampering slightly differently.

PersistentTokenBasedRememberMeServices creates a unique series identifier per user, with unique tokens within that series, as the user continues to interact and be authenticated by the site. The combination of series and token are stored in the cookie, and used to authenticate the user against the persistent token store. Both series and token are randomly generated, and of configurable length, making the likelihood of successful brute force guessing by a malicious attacker extremely small.

Just like TokenBasedRememberMeServices, persistent tokens may be compromised by cookie theft or other man-in-the-middle techniques. The use of a custom subclass incorporating the IP address into the persistent token, as well as forcing username and password authentication for sensitive areas of the site, are still advised when using persistent tokens.

Securing your site with SSL

It is highly likely that you have both heard of and used SSL encryption in your daily online life. The Secure Sockets Layer (SSL) protocol, and its successor, Transport Layer Security (TLS), are used to provide transport level security for HTTP transactions over the web—these are known as HTTP Secure (HTTPS) transactions.

In summary, SSL and TLS are used to secure the raw HTTP data being transmitted between the browser client and the web server in a way that is transparent to the user. As a developer, however, it’s of critical importance to plan for the use of SSL in the design of a secure website. Spring Security provides a number of configuration options that allow for fl exible incorporation of SSL in your web application.

Although SSL and TLS are different protocols (TLS being the more
mature and recent iteration of the protocol), most people are familiar with
the term SSL, and as such we will use this term to refer to both SSL and
TLS protocols for the remainder of this book.

While a detailed examination of the mechanics of the SSL protocol are beyond the scope of this book, several excellent books and technical papers exist, which describe the specifications and protocols in very fine detail (you may want to start with RFC 5246, The Transport Layer Security (TLS) Protocol Version 1.2, at http://tools.ietf. org/html/rfc5246).

Setting up Apache Tomcat for SSL

First and foremost, if you’re planning on following along with the SSL-related examples, you’ll need to configure your application server to support SSL connections. For Apache Tomcat, this is relatively easy; if you are using another application server, please consult the relevant sections of the documentation.

Generating a server key store

We’ll need to use the Java keytool command to generate a key store. Open a command prompt and enter the following command:

	keytool -genkeypair -alias jbcpserver -keyalg RSA -validity 365
	-keystore tomcat.keystore -storetype JKS

Follow the prompts using the following directions. Enter the password password for the key store and private key password.

	What is your first and last name?
		[Unknown]: JBCP Pets Admin
	What is the name of your organizational unit?
		[Unknown]: JBCP Pets
	What is the name of your organization?
		[Unknown]: JBCP Pets
	What is the name of your City or Locality?
		[Unknown]: Anywhere
	What is the name of your State or Province?
		[Unknown]: NH
	What is the two-letter country code for this unit?
		[Unknown]: US
	Is CN=JBCP Pets Admin, OU=JBCP Pets, O=JBCP Pets, L=Anywhere, ST=NH, C=US
	correct?
		[no]: yes

This will result in the creation of a file named tomcat.keystore in the current directory. This is the key store that will be used to enable Tomcat SSL.

Be aware that the command genkeypair was called (genkey in
pre-Java 6 releases of keytool).

Remember the location of this file for the next step.

Configuring Tomcat’s SSL Connector

In Apache Tomcat’s conf directory, open server.xml in an XML editor (Eclipse or equivalent will be fine), and uncomment or add the SSL Connector declaration. It
should look as follows:

	<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
		maxThreads="150" scheme="https" secure="true"
		sslProtocol="TLS"
		keystoreFile="conf/tomcat.keystore"
	keystorePass="password"/>

Ensure the tomcat.keystore file you created in the previous step is copied to the conf directory of the Tomcat installation. After this configuration, the Tomcat server can be started, and the JBCP Pets application should be accessible on a secure port, at https://localhost:8443/JBCPPets/.

Take care to include the https and not http—depending on the browser, this problem may go undetected, and you may find yourself scratching your head as to why you are not seeing the JBCP Pets home page.

Automatically securing portions of the site

It seems reasonable to assume that if you’ve gone to the trouble of setting up SSL to secure your customers’ data, you would always want certain areas of the site to fall under the umbrella of SSL protection. Fortunately, Spring Security makes this easy, with the simple step of adding a configuration property to the declarations.

The attribute requires-channel can be added to any declaration to require that any URL matching the pattern is required to pass over a specific protocol (HTTP, HTTPS, or any). If we secure the JBCP Pets site in this way, the configuration would be as follows:

	<http auto-config="true" use-expressions="true">
		<intercept-url pattern="/login.do" access="permitAll"
			requires-channel="https"/>
		<intercept-url pattern="/account/*.do"
			access="hasRole('ROLE_USER') and fullyAuthenticated"
			requires-channel="https"/>
		<intercept-url pattern="/*" access="permitAll"
			requires-channel="any"/>
		<!-- ... -->
	</http>

If we start the application at this point, we see the following behavior:

  • Access to the login page and the account page, now requires HTTPS,and the browser will automatically redirect the user from the non-secure
    (HTTP) URL to the secure URL. For example, attempts to access http://localhost:8080/JBCPPets/login.do will be redirected to https://localhost:8443/JBCPPets/login.do.
  • Once the user has been switched to the HTTPS-secured URL, if he accesses a URL that isn’t required to use HTTPS, he can still remain on HTTPS.

We can imagine that the important security benefits of this type of configuration— most modern application servers use the secure indicator on session cookies, so enforcing the login page to be secure (if this is where your application’s sessions are first allocated) will ensure that the session cookie is transferred securely, and is less subjected to session hijacking. Additionally, this wires rules about SSL encryption directly into your security declarations, so it’s very easy to ensure that all sensitive pages in the application are properly and thoroughly secured.

The functionality of automatically redirecting users to the appropriate protocol (HTTP or HTTPS) is implemented by the addition of another servlet filter towards the front of the Spring Security filter chain (just after the SecurityContextPersistenceFilter). The o.s.s.web.access.channel.ChannelProcessingFilter is automatically placed in the filter chain if any URL declarations are indicated to require a particular protocol, using the requires-channel attribute.

The interaction of the ChannelProcessingFilter in the processing of the request is illustrated in the following figure:

14The design of the ChannelProcessingFilter lends itself to extension or augmentation, should your application require more complex logic than ships out of the box. Please note that although we illustrate only the SecureChannelProcessor and RetryWithHttpsEntryPoint implementation classes in the diagram, similar classes exist to validate and act on URLs that are declared to require HTTP.

It’s important to note that, since the ChannelEntryPoint performs simple URL rewriting with an HTTP 302 redirect, it is of course not possible to use this technique to redirect POST URLs (although typically a POST should not transition between secure and insecure protocols anyway, since most browsers will warn against
this behavior).

Secure port mapping

Certain environments may have HTTP or HTTPS ports other than the standard defaults of 80/443 or 8080/8443. In this case, you must augment your application’s configuration to include explicit port mappings, so that the ChannelEntryPoint implementations can determine which port to use when redirecting users to secure or non-secure URLs.

This is trivial to do with the additional configuration element , which allows for specification of additional HTTP or HTTPS pairs in addition
to the defaults:

	<port-mappings>
		<port-mapping http="9080" https="9443"/>
	</port-mappings>

The use of port mappings can be especially important if your application server is behind a reverse proxy.

Summary

In this chapter, we have:

  • Introduced the configuration to support a permanent security data store
    using a JDBC-compatible database.
  • Configured JBCP Pets to use the database for user authentication and highly secure password storage, using password encryption and salting techniques.
  • Evaluated techniques for managing users persisted to a database using JDBC.
  • Configured user assignment into security groups, conferring roles, rather than direct role assignment. This increases the manageability of the site and
    its user community.
  • Explored the use of Spring Security with a legacy (non-default) database schema.
  • Examined configuration and application design techniques used to incorporate HTTPS to increase the security of data transferred to and from
    secured areas of the application.

In the next chapter, we’ll explore some more advanced authorization capabilities of Spring Security, and introduce the Spring Security JSP tag library for fine-grained authorization.

also read:

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Arthur Ronald says:

    Congratulations for sharing your knowledge! A in-depth overview of many features of Spring security.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better