STEP1.  openeg 프로젝트에 스프링시큐리티3 라이브러리를 추가한다.

아래 3개파일을 /WEB-INF/lib 폴더로 다운로드 한다.






STEP2.  /WEB-INF/openeg-security.xml 파일을 생성한다.


생성하기 어려우면 아래 첨부파일을 다운로드 받아 넣는다. ^^


STEP3. /WEB-INF/web.xml 에 필터 추가


모두 요청에 대해 springSecurity가 적용되도록 필터를 설정한다.

아래 첨부파일을 다운로드 받아서 springSecurityFilterChain 부분만 복사해서 넣는다.

STEP2에 작성한 openeg-security.xml 이 springMVC 서블릿과 관련설정파일이 로드되기전에 추가로 로드되도록  ApplicationContext를 선언한다.

첨부된 web.xml 파일에서  <context-param> 설정 부분을 복사해서 사용한다.


STEP4. 기본적인 설정완료!!


Spring Security 가 동작하는지 확인해보자. 서버를 구동하고 http://localhost:8080/openeg/test.jsp  페이지를 요청하면 기본적인 보안 레이어가 구현되어 인증화면이 나타는 것을 볼 수 있다.

사용자명과 비밀번호, 사용자역할을 openeg-security.xml 파일에서 하드코딩했다.

guest,guest로 로그인한다.

<authentication-manager alias="authenticationManager">



<user authorities="ROLE_USER" name="guest" 





[추가적으로 해결해야 할 문제들]

1. 사용자계정을 이렇게는사용하기 힘들고(모든 계정을 XML파일에 등록할 수는 없으니^^) 데이터베이스 기반의 인증 프로바이더를 사용하여 해결한다.

2. 쇼핑몰이라면 로그인하지 않고 물건을 검색하는것이 가능해야 하는데 이예제는 이 사이트에 접속하면 무조건 "인증받아라"  구조이다.  이것은  사용자의 역할 정의를 통해서 해결한다.

3. 예제 사이트에 접속하면 무조건 밋밋한 로그인 페이지를 만나게 된다. 쇼핑몰이라면 헐~~ 이것다.  이건 로그인 폼을 추가해서 해결한다.

스프링 시큐리티 3  참고자료

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:

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

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

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:

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

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:

1insert into users(username, password, enabled) values
2    ('admin','admin',true);
3insert into authorities(username,authority) values
4    ('admin','ROLE_USER');
5insert into authorities(username,authority) values
6    ('admin','ROLE_ADMIN');
7insert into users(username, password, enabled) values
8    ('guest','guest',true);
9insert into authorities(username,authority) values
10    ('guest','ROLE_USER');

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

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

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 package:

1public class CustomJdbcDaoImpl extends JdbcDaoImpl implements
2IChangePassword {
3    public void changePassword(String username, String password) {
4        getJdbcTemplate()
6            password, username);
7    }

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:

1<bean id="jdbcUserService"
2    class="">
3    <property name="dataSource" ref="dataSource"/>

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:

1<bean id="jdbcUserService"
2        class="
3            .provisioning.JdbcUserDetailsManager">
4    <property name="dataSource" ref="dataSource"/>
5    <property name="authenticationManager"
6        ref="authenticationManager"/>

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:

1<h2>Change Password</h2>
2    <form method="post">
3        <b><label for="oldpassword">Old Password</label>:
4        <input id="oldpassword" name="oldpassword"
5            size="20" maxlength="50" type="password"/>
6        <br /></b>
7        <label for="password">New Password</label>:
8        <input id="password" name="password" size="20"
9            maxlength="50" type="password"/>
10        <br />

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

2private 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:

1public String submitChangePasswordPage(@RequestParam("oldpassword")
2        String oldPassword,
3    @RequestParam("password") String newPassword) {
4        userDetailsManager.changePassword(oldPassword, newPassword);
5        SecurityContextHolder.clearContext();
6        return "";
7    }

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:

1<bean id="jdbcUserService"
2    class="">
3    <property name="dataSource" ref="dataSource"/>
4    <b><property name="enableGroups" value="true"/>
5    <property name="enableAuthorities" value="false"/></b>

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:

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

Next, assign roles to groups:

1insert into group_authorities(group_id, authority) select id,'ROLE_
2USER' from groups where group_name='Users';
3insert into group_authorities(group_id, authority) select id,'ROLE_
4USER' from groups where group_name='Administrators';
5insert into group_authorities(group_id, authority) select id,'ROLE_
6ADMIN' from groups where group_name='Administrators';

Next, create the users:

1insert into users(username, password, enabled) values
3insert into users(username, password, enabled) values

Finally, assign users to groups:

1insert into group_members(group_id, username) select id,'guest' from
2groups where group_name='Users';
3insert into group_members(group_id, username) select id,'admin' from
4groups 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:

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

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.

1<bean id="jdbcUserService"
2    class="">
3    <property name="dataSource" ref="dataSource"/>
4    <property name="enableGroups" value="true"/>
5    <property name="enableAuthorities" value="false"/>
6    <b><property name="usersByUsernameQuery">
7        <value>SELECT LOGIN, PASSWORD,
8            1 FROM USER_INFO WHERE LOGIN = ?
9        </value>
10    </property>
11    <property name="groupAuthoritiesByUsernameQuery">
13            FROM USER_INFO U
18            WHERE U.LOGIN = ?
19        </value>
20    </property></b>

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:

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

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:

1<bean class="
2    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:

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

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, DatabasePasswordSecurerBean, is fairly simple.

1public class DatabasePasswordSecurerBean extends