Reader small image

You're reading from  Spring Security - Third Edition

Product typeBook
Published inNov 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781787129511
Edition3rd Edition
Languages
Tools
Right arrow
Authors (3):
Mick Knutson
Mick Knutson
author image
Mick Knutson

With nearly two decades of experience working in the IT industry in various roles as Enterprise technology consultant, Java Architect, project leader, Engineer, Designer and Developer, Mr. Knutson has gained a wide variety of experience in disciplines including JavaEE, Web Services, Mobile Computing and Enterprise Integration Solutions. Over the course of his career, Mr. Knutson has enjoyed long lasting partnerships with many of the most recognizable names in the Health Care, Financial, Banking, Insurance, Manufacturing, Telecommunications, Utilities, Product Distribution, Industrial and Electronics industries employing industry standard full software life cycle methodologies including the Rational Unified Process (RUP), Agile, SCRUM, and Extreme Programming (XP). Mr. Knutson has also undertaken speaking engagements, training seminars, white paper and book publishing engagements world-wide. As an active Blogger and tweeter, Mr. Knutson has also been inducted in the prestigious DZone.com Most Valuable Blogger (MVB) group and can be followed at http://www.dzone.com/page/mvbs, http://www.dzone.com/users/mickknutson and twitter at http://twitter.com/mickknutson.
Read more about Mick Knutson

Peter Mularien
Peter Mularien
author image
Peter Mularien

Peter Mularien is an experienced software architect and engineer, and the author of the book Spring Security 3, Packt Publishing. Peter currently works for a large financial services company and has over 12 years consulting and product experience in Java, Spring, Oracle, and many other enterprise technologies. He is also the reviewer of this book.
Read more about Peter Mularien

View More author details
Right arrow

JDBC-Based Authentication

In the previous chapter, we saw how we can extend Spring Security to utilize our CalendarDao interface and our existing domain model to authenticate users. In this chapter, we will see how we can use Spring Security's built-in JDBC support. To keep things simple, this chapter's sample code is based on our Spring Security setup from Chapter 2, Getting Started with Spring Security. In this chapter, we will cover the following topics:

  • Using Spring Security's built-in JDBC-based authentication support
  • Utilizing Spring Security's group-based authorization to make administering users easier
  • Learning how to use Spring Security's UserDetailsManager interface
  • Configuring Spring Security to utilize the existing CalendarUser schema to authenticate users
  • Learning how we can secure passwords using Spring Security's new cryptography module...

Required dependencies

Our application has already defined all the necessary dependencies required for this chapter. However, if you are using Spring Security's JDBC support, you are likely going to want the following dependencies listed in your build.gradle file. It is important to highlight that the JDBC driver that you will use will depend on which database you are using. Consult your database vendor's documentation for details on which driver is needed for your database.

Remember that all the Spring versions need to match, and all Spring Security versions need to match (this includes transitive dependency versions). If you are having difficulty getting this to work in your own application, you may want to define the dependency management section in build.gradle to enforce this, as shown in Chapter 2, Getting Started with Spring Security. As previously mentioned, you...

Using the H2 database

The first portion of this exercise involves setting up an instance of the Java-based H2 relational database, populated with the Spring Security default schema. We'll configure H2 to run in memory using Spring's EmbeddedDatabase configuration feature—a significantly simpler method of configuration than
setting up the database by hand. You can find additional information on the H2 website at http://www.h2database.com/.

Keep in mind that in our sample application, we'll primarily use H2 due to its ease of setup. Spring Security will work with any database that supports ANSI SQL out of the box. 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...

The default user schema of Spring Security

Let's take a look at each of the SQL files used to initialize the database. The first script we added contains the default Spring Security schema definition for users and their authorities. The following script has been adapted from Spring Security's Reference, which is listed in the Appendix, Additional Reference Material to have explicitly named constraints, to make troubleshooting easier:

    //src/main/resources/database/h2/security-schema.sql

create table users(
username varchar(256) not null primary key,
password varchar(256) not null,
enabled boolean not null
);
create table authorities (
username varchar(256) not null,
authority varchar(256) not null,
constraint fk_authorities_users
foreign key(username) references users(username)
);
create unique index ix_auth_username...

The UserDetailsManager interface

We have already leveraged the InMemoryUserDetailsManager class in Spring Security in Chapter 3, Custom Authentication, to look up the current CalendarUser application in our SpringSecurityUserContext implementation of UserContext. This allowed us to determine which CalendarUser should be used when looking up the events for the My Events page. Chapter 3, Custom Authentication, also demonstrated how to update the DefaultCalendarService.java file to utilize InMemoryUserDetailsManager, to ensure that we created a new Spring Security user when we created CalendarUser. This chapter reuses exactly the same code. The only difference is that the UserDetailsManager implementation is backed by the JdbcUserDetailsManager class of Spring Security, which uses a database instead of an in-memory datastore.

What other features does UserDetailsManager provide out...

Support for a custom schema

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 JdbcDaoImpl to map to it.

We will now update Spring Security's JDBC support to use our existing CalendarUser database along with a new calendar_authorities table.

We can easily change the configuration of JdbcUserDetailsManager to utilize this schema and override Spring Security's expected table definitions and columns, which we're using for the JBCP calendar application.

Determining the correct JDBC SQL queries

The JdbcUserDetailsManager...

Configuring secure passwords

You might 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 (plaintext)
  • Passwords supplied by the user must be compared to the 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...

The PasswordEncoder method

Password hashing in Spring Security is encapsulated and defined by implementations of the o.s.s.authentication.encoding.PasswordEncoder interface. The simple configuration of a password encoder is possible through the passwordEncoder() method within the AuthenticationManagerBuilder element, as follows:

    auth
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(CUSTOM_USERS_BY_USERNAME_QUERY)
.authoritiesByUsernameQuery(CUSTOM_AUTHORITIES_BY_USERNAME_QUERY)
.passwordEncoder(passwordEncoder());

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 following table provides a list of the out-of-the-box implementation classes and their benefits. Note that all implementations reside...

Using salt in Spring Security

Spring Security 3.1 provides a new cryptography module that is included in the spring-security-core module and is available separately in spring-security-crypto. The crypto module contains its own o.s.s.crypto.password.PasswordEncoder interface. In fact, using this interface is the preferred method for encoding passwords, because it will salt passwords using a random salt. At the time of this writing, there are the following three implementations of o.s.s.crypto.password.PasswordEncoder:

Class

Description

o.s.s.crypto.bcrypt.BCryptPasswordEncoder

This class uses the bcrypt hashing function. It supports salt and the ability to slow down to perform over time as technology improves. This helps protect against brute-force search attacks.

o.s.s.crypto.password.NoOpPasswordEncoder

This class does no encoding (it returns the password in...

Trying out the salted passwords

Start up the application and try creating another user with the password user1. Use the H2 console to compare the new user's password, and observe that they are different.

Your code should now look like this: calendar04.05-calendar.

Spring Security now generates a random salt and combines this with the password before hashing our password. It then adds the random salt to the beginning of the password in plaintext, so that passwords can be checked. The stored password can be summarized as follows:

    salt = randomsalt()
hash = hash(salt+originalPassword)
storedPassword = salt + hash

This is the pseudocode for hashing a newly created password.

To authenticate a user, salt and hash can be extracted from the stored password, since both salt and hash are fixed lengths. Then, the extracted hash can be compared against a new hash, computed...

Summary

In this chapter, we learned how to use Spring Security's built-in JDBC support. Specifically, we have learned that Spring Security provides a default schema for new applications. We also explored how to implement GBAC and how it can make managing users easier.
We also learned how to integrate Spring Security's JDBC support with an existing database and also how to secure our passwords by hashing them and using a randomly-generated salt.

In the next chapter, we will explore the Spring Data project and how to configure Spring Security to use object-relational mapping (ORM) to connect to an RDBMS, as well as a document database.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Spring Security - Third Edition
Published in: Nov 2017Publisher: PacktISBN-13: 9781787129511
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (3)

author image
Mick Knutson

With nearly two decades of experience working in the IT industry in various roles as Enterprise technology consultant, Java Architect, project leader, Engineer, Designer and Developer, Mr. Knutson has gained a wide variety of experience in disciplines including JavaEE, Web Services, Mobile Computing and Enterprise Integration Solutions. Over the course of his career, Mr. Knutson has enjoyed long lasting partnerships with many of the most recognizable names in the Health Care, Financial, Banking, Insurance, Manufacturing, Telecommunications, Utilities, Product Distribution, Industrial and Electronics industries employing industry standard full software life cycle methodologies including the Rational Unified Process (RUP), Agile, SCRUM, and Extreme Programming (XP). Mr. Knutson has also undertaken speaking engagements, training seminars, white paper and book publishing engagements world-wide. As an active Blogger and tweeter, Mr. Knutson has also been inducted in the prestigious DZone.com Most Valuable Blogger (MVB) group and can be followed at http://www.dzone.com/page/mvbs, http://www.dzone.com/users/mickknutson and twitter at http://twitter.com/mickknutson.
Read more about Mick Knutson

author image
Peter Mularien

Peter Mularien is an experienced software architect and engineer, and the author of the book Spring Security 3, Packt Publishing. Peter currently works for a large financial services company and has over 12 years consulting and product experience in Java, Spring, Oracle, and many other enterprise technologies. He is also the reviewer of this book.
Read more about Peter Mularien