, , , ,

This is part 6 of the tutorial series for building a web application using Spring Boot. In this post we look at adding a DAO Authentication provider for Spring Security.

We started off with the first part by creating our Spring project using the Spring Initializr. In part 2, we rendered a web page using Thymeleaf and Spring MVC. This was followed by part 3 where we looked at setting up Spring Data JPA for database persistence. Part 4 was all about consolidating everything to provide a working Spring Boot MVC Web Application capable of performing CRUD operations.

In the previous part 5 of this series, we configured a basic in-memory authentication provider. It’s a good starting point to learn Spring Security, but as I mentioned there, it’s not for enterprise applications. A production-quality implementation would likely use the DAO authentication provider.

In this part of the series, I will discuss Spring Security with the DAO authentication provider to secure our Spring Boot Web application. We will implement both authentication and role-based authorization with credentials stored in the H2 database. For persistence, we will use the Spring Data JPA implementation of the repository pattern, that I covered in part 3. Although there are several Spring Data JPA implementations, Hibernate is by far the most popular.

As the Spring Data JPA dependency is included in our Maven POM, Hibernate gets pulled in and configured with sensible default properties via Spring Boot.

This post builds upon 5 previous posts. If you’re not familiar with all the content around Spring, I suggest you to go through this series from the start.

JPA Entities

Our application already has a Product JPA entity. We’ll add two more entities, User and Role. Following the SOLID design principle’sprogram to interface ” principle, we will start by writing an interface followed with an abstract class for our entities.

DomainObject.java

AbstractDomainClass.java

The entity classes are as follows.

User.java

Role.java

The User and Role JPA entities are part of the many-to-many relationship. Also, in Line 15 of the User class, notice that the password field is marked as @Transient.

That’s because we don’t want to store the password in text form.

Instead, we will store the encrypted form of the password.

JPA Repositories

Spring Data JPA provides the CRUD Repository feature. Using it, we just define the repository interfaces for our User and Role entities to extend CrudRepository.

The Spring Data JPA repositories for the User and Role entities are as follows.

UserRepository.java

RoleRepository.java

By extending CrudRepository, both the repositories inherit several methods for working with entity persistence, including methods for saving, deleting, and finding entities. Spring Data JPA uses generics and reflection to generate the concrete implementations of both the interfaces.

Spring Data JPA Services

We can now create the services, that will use Spring Data JPA to perform CRUD operations on the User and Role entities.

Of course, we will follow the Interface Segregation principle to maintain loose coupling. It’s always best to “program to interface”, especially when leveraging the benefits of Spring’s dependency injection.

So, let’s start with the service interfaces.

CRUDService.java

UserService.java

RoleService.java

Both RoleService and UserService extends CRUDService that defines the basic CRUD operations on entities. UserService, with the additional findByUsername() method is a more specialized service interface for CRUD operations on User.

We have made the service interfaces generic to mask our service implementations using the Façade design pattern. The implementations can be Spring Data JPA with repository, DAO, or Map patterns, or even plain JDBC, or some external Web service. The client code does not need not to be aware of the implementation. By using interfaces, we are able to leverage multiple concrete implementations of the services.

We’ll write the service implementation classes using the Spring Data JPA repository pattern.

UserServiceImpl.java

In this class, we auto-wired in UserRepository and EncryptionService. Going ahead, we will create EncryptionService using the Jasypt library to add encryption capabilities for storing user passwords. The overridden methods of this class use the UserRepository we created to perform CRUD operations on User.

The RoleServiceImpl provides a similar implementation for RoleService.

RoleServiceImpl.java

Free Spring TutorialPassword Encryption Service

The Jasypt library provides an implementation for unidirectional encryption. We will use Jasypt to encrypt a password before storing it to the database. For authentication, we will provide Jasypt the received password. Under the hood, Jasypt will encrypt the received password and compare it to the stored one.

Let’s add the Jasypt dependency to our Maven POM.

Note: The latest available Jasypt 1.9.2 targets Spring Security 3. But even for Spring Security 4 that we are using, Jasypt doesn’t have compatibility issues.

With Jasypt pulled in, we will write a bean for StrongPasswordEncryptor of Jasypt – a utility class for easily performing high-strength password encryption and checking. The configuration class, CommonBeanConfig is this.

CommonBeanConfig.java

Our generic EncryptionService interface will define two methods to encrypt and compare passwords.

EncryptionService.java

The implementation class is this.

EncryptionServiceImpl.java

In this implementation class, we autowired the StrongPasswordEncryptor bean. In Line 18, the encryptPassword() method encrypts the password passed to it. In Line 22, the checkPassword() method returns a boolean result of the password comparison.

User Details Service Implementation

Spring Security provides a UserDetailsService interface to lookup the username, password and GrantedAuthorities for any given user. This interface provides only one method, loadUserByUsername(). This method returns an implementation of Spring Security’s UserDetails interface that provides core user information.

The UserDetails implementation of our application is this.

UserDetailsImpl.java

In this class, we have defined the fields of our data model and their corresponding setter methods. The SimpleGrantedAuthority we set on Line 16 is a Spring Security implementation of an authority that we will convert from our role. Think of an authority as being a “permission” or a “right” typically expressed as strings.

We need to provide an implementation of the loadUserByUsername() method of UserDetailsService. But the challenge is that the findByUsername() method of our UserService returns a User entity, while Spring Security expects a UserDetails object from the loadUserByUsername() method.

We will create a converter for this to convert User to UserDetails implementation.

UserToUserDetails.java

This class implements the Spring Core Coverter  interface and overrides the convert() method that accepts a User object to convert. In Line 16, the code instantiates a UserDetailsImpl object, and from Line 19 – Line 26, the code initializes the UserDetailsImpl object with data from User.

With the converter ready, it’s now easy to implement the UserDetailsService interface. The implementation class is this.

Here is our implemention.

UserDetailsServiceImpl.java

In the UserDetailsServiceImpl class, we auto wired in UserService and Converter. In Line 31, the lone overridden method loadUserByUsername() converts a User to UserDetails by calling the convert() method of Converter.

Security Configuration

The current security configuration class, SpringSecConfig extends WebSecurityConfigurerAdapter to configure two things. An authentication provider and the application routes to protect. Our route configuration will remain the same. However, we need to register the DAO authentication provider for use with Spring Security.

We will start by setting up a password encoder to encode passwords present in the UserDetails object returned by the configured UserDetailsService. We will define a new bean for Spring Security’s PasswordEncoder that takes in the StrongPassordEncryptor bean.

Remember that we created StrongPassordEncryptor earlier in the CommonBeanConfig Spring configuration class?

Next, we will set up the DAO authentication provider, like this.

In this code, we passed the previously configured PasswordEncoder and UserDetailsService to daoAuthenticationProvider(). The PasswordEncoder is going to use the Jasypt library for encoding the password and verifying that the passwords match. The UserDetailsService will fetch the User object from the database and hand over to Spring Security as a UserDetails object. In the method, we instantiated the DaoAuthenticationProvider and initialized it with the PasswordEncoder and UserDetailsService implementations.

Next, we need to auto wire in the AuthenticationProvider as we want the Spring Context to manage it.

We will also auto wire in the AuthenticationManagerBuilder. Spring Security will use this to set up the AuthenticationProvider.

The complete SpringSecConfig class is this.

SpringSecConfig.java

Application Bootstrapping with Seed Data

For seed data of the application, we have an ApplicationListener implementation class that gets called upon the ContextRefresedEvent on startup. In this class, we will use Spring to inject the UserRepository and RoleRepository Spring Data JPA repositories for our use. We will create two User and two Role entities and save them to the database when the application starts. The code of this class is this.

SpringJpaBootstrap.java

This class in addition to loading product data, invokes the following methods to load users and roles at startup:

  • loadUsers(): Stores two User entities. One with “user” and the other with “admin” as both the user name and password.
  • loadRoles(): Stores two Role entities for the “USER” and “ADMIN” roles.
  • assignUsersToUserRole(): Assigns the User with username “user” to the “USER” role.
  • assignUsersToAdminRole(): Assigns the User with username “admin” to the “ADMIN” role.

Free Spring TutorialThymeleaf Extras module

In the previous part 5 of this series, I discussed the Thymeleaf “extras” integration module to integrate Spring Security in our Thymeleaf templates. Things will largely remain unchanged in this presentation layer, except for two instances.
Currently, both USER and ROLE are being referred from the presentation layer code as ROLE_USER and ROLE_ADMIN. This was required because we relied on Spring Security’s in-memory authentication provider for managing our users and roles, and Spring Security’s internal feature maps a configured role to the role name prefixed with ROLE_. With the DAO authentication provider, our roles are mapped to authorities as it is (We did this in in the UserToUserDetails converter), and we can refer them directly from code as USER and ADMIN.

The second change is brought in by GrantedAuthority used by the Spring Security UserDetails interface. If you recall, we mapped our Role implementation to SimpleGrantedAuthority in the UserToUserDetails converter.

Therefore, in the Thymeleaf templates, we need to change the hasRole() and hasAnyRole() authorization expressions to hasAuthority() and hasAnyAuthorities().

The affected templates are header.html and products.html.

header.html

products.html

Running the Application

Our application is configured to run the H2 database console, which I have explained here. So, when you run the application, you’ll now be able to access the H2 database console at http://localhost:8080/console. You can use it to view the initial authentication-related data loaded by the SpringJpaBootstrap class.
USER Table for Spring Security
Role Table for Spring Security

This is how the home page appears to authenticated users with USER and ADMIN roles.

Home Page View for USER Role
Home Page View for ADMIN Role

With our Security configuration, this is how the product listing page appears to users with different roles.

Home Page View for Anonymous
Home Page View for USER Role
Home Page View for ADMIN Role

Summary

Spring Security has a large scope, and what we configured is only a small part of it. Spring Security supports XML-based and annotation-based finer level security configurations. With Spring Security, we can secure websites down to specific URLs, assign roles to URL, and even roles to different HTTP actions – a security configuration typically employed in RESTful APIs.

What makes Spring Security great is that you can easily hook in another security provider. If you noticed, we hardly made any change in the presentation and business logic layers while transitioning from the earlier basic in-memory authentication provider to the DAO provider. We could also use LDAP, Single Sign-On (SSO), OpenID, and OAuth 2.0 providers. It all depends on the requirements of your application.

Get the Source!

The full source code for this example is available here on GitHub.

0
Share
, , ,

This is the fifth part of my tutorial series on building a Spring Boot Web Application. We started off in the first part looking at using the Spring Initializr to start our Spring Boot project. In part 2, we configured Spring MVC and ThymeLeaf templates to display a basic web page. This was followed by part 3 where we setup the H2 database and Spring Data JPA and used them to persist data of our application to the database. In part 4, we consolidated everything to provide a working Spring Boot MVC Web Application capable of performing CRUD operations. We now have an application which displays data from the database, allows you to create new records, update existing records, and delete selected records too.

In part 5, we will use Spring Security to set up authentication and authorization in our application.

Spring Security, one of the most commonly used project in the Spring family of projects, provides a powerful and highly customizable authentication and authorization framework designed specifically to secure Java applications. In this part, I’ll show you how to setup Spring Security to secure our Spring Boot Web Application using the basic in-memory authentication provider.

Security Requirements

Our Spring Boot Web application in the current state is accessible to all users. Any user can create and view products, and also edit or delete them. Before we setup Spring Security to secure our application, let’s set few security requirements:

  • An anonymous user (user who doesn’t sign in) should be able to view the home page and product listing.
  • An authenticated user, in addition to the home page and product listing, should be able to view the details of a product.
  • An authenticated admin user, in addition to the above, should be able to create, update, and delete products.

Maven Dependencies

Spring Security is already listed as a dependency of our application in the Maven POM.

In the Maven Projects pane of IntelliJ we can see the additional dependencies of  Spring Security.

spring security dependencies in Maven

As we can see the Spring Security starter has brought in Spring AOP, Spring Security web, and Spring Security config, which in turn bring in Spring Security core.

Authentication and Authorization

Before we go deep, we need to understand what authentication and authorization means in Spring Security. Although both sound similar and it’s very easy to confuse them..

Authentication means ascertaining that somebody really is who they claim to be. Authentication is performed using different mechanisms. One simple and common mechanism is through user credentials in the form of user name and password. These are stored in some type back end data store, such as a SQL database. Others include LDAP, Single Sign-On (SSO), OpenID, and OAuth 2.0.

Authorization, on the other hand, defines what you are allowed to do. For example, an authenticated user may be authorized to view products but not to add or delete them.

Remember that authentication is “Who I am?” as a user to the system. While authorization is “You are either allowed or not to do this” from the system.

Securing URLs

In part 1, where we added Spring Security into our build, Spring Boot configured Spring Security to require Basic authentication for all endpoints. In part 2, we configured Spring Security to allow all requests access to the root path. We did this by creating a SecurityConfiguration class that extends the WebSecurityConfigurerAdapater class and overridden the configure() method. We will now update the same configure() method to define which URL paths should be secured and which should not.

Here is the the updated configure() method:

This security configuration will:

  • Allows all requests to the /, /products, /product/show/*, /console/** paths (Line 5)
  • Secures all other paths of the application to require authentication (Line 6)
  • Allows everyone to view a custom /login page specified by loginPage()(Line 8)
  • Permits all to make logout calls (Line 10)
  • Disables CSRF protection (Line 12)
  • Disables X-Frame-Options in Spring Security (Line 13) for access to H2 database console. By default, Spring Security will protect against CRSF attacks.

Note: Although this is not a production-level configuration, it should get us started with the basic in-memory authentication. I’ll revisit this part, when I discuss more advanced security configuration in my upcoming posts.

In the same SecurityConfiguration class, we will also autowire a configureGlobal() overridden method of WebSecurityConfigurerAdapter. At runtime, Spring will inject an AuthenticationManagerBuilder that we will use to configure the simplest, default in-memory authentication with two users. The complete code of the
SecurityConfiguration class is this.

SecurityConfiguration.java

In this code, Line 27 – Line 30 configures in-memory authentication with two users. The first user with the username user and a password user is assigned a role of USER. The second user with the username admin and a password admin is assigned a role of ADMIN.

The Login Page

Our application will have a login page to capture user credentials in the form of user name and password. The login page, a Thymeleaf template will be served whenever a request to /login is received. We will configure the request mapping in ProductController like this.

The code of the login template is this.

login.html

This is a standard Thymeleaf template that presents a form to capture a username and password and post them to /login. Spring Security provides a filter that intercepts that request and authenticates the user with our configured in-memory authentication provider. If authentication succeeds, the application displays the requested page. If authentication fails, the request is redirected to /login?error and the login page displays the appropriate error message (Line 10 – Line 12). Upon successfully signing out, our application is sent to /login?logout and the login page displays a sign out message (Line 13 – Line 17).

This is how the login page displays an error message on authentication failure.
Spring Security Login Error Message

Spring Security Integration in Thymeleaf

To integrate Spring Security in our Thymeleaf templates, we will use the Thymeleaf “extras” integration module for Spring Security. For this, we need to add a JAR dependency in our Maven POM like this.

The Thymeleaf “extras” module is not a part of the Thymeleaf core but fully supported by the Thymeleaf team. This module follows its own schema, and therefore we need to include its XML namespace in those templates that will use security features, like this.

Showing Content based on Role

One of our application requirement states that only authenticated users with the ADMIN role can create products. To address this, we will configure authorization in the header.html Thymeleaf fragment to display the Create Product link only to users with the ADMIN role. In this template, we will also display a welcome message with the user name to an authenticated user. The code of the header.html template file is this:

header.html

The Thymeleaf security extension provides the sec:authorize attribute that renders its content when the corresponding Spring Security expression evaluates to true.

In Line 16 we used the sec:authorize attribute to display the Create Product link only if the authenticated user has the ADMIN role. Observe that we are checking against ROLE_ADMIN instead of the ADMIN role. This is because of Spring Security’s internal feature of mapping a configured role to the role name prefixed with ROLE_. In Line 23 we again used the sec:authorize attribute to check whether the user is authenticated, and if so, displayed the name using the sec:authenticate attribute.

This is how the home page appears to authenticated users with USER and ADMIN roles.

Home Page View for USER Role
Home Page View for ADMIN Role

Our current Product Listing page rendered by the products.html template displays the View, Edit, and Delete links to all users. In this template, we will configure authorization:

  • To show the View, Edit, and Delete links to a user with ADMIN role
  • To show only the View link to a user with USER role
  • Not to show any links to an anonymous user who hasn’t signed in

The code of the products.html page is this.

products.html

In Line 16 the “Sign Out” form submits a POST to /logout. Upon successfully logging out it will redirect the user to /login?logout. The remaining authorization is performed using the sec:authorize attribute. The hasAnyRole('ROLE_USER','ROLE_ADMIN') expression on Line 30 and Line 39 evaluates to true if the user has either the ROLE_USER or ROLE_ADMIN.

With this configuration, the product listing page will appear to different roles like this.

Home Page View for Anonymous
Home Page View for USER Role
Home Page View for ADMIN Role
If you are wondering why the Sign Out Submit button is getting displayed as a link, it’s due to this CSS code I added to the guru.css stylesheet.

guru.css

The code of productshow.html and productform.html templates, except for the addition of the “Sign Out” form, remains the same.

productshow.html

productform.html

Finally, if any signed in user clicks on Sign Out in any one of the secured pages, the user is redirected to the login page with a message, like this.
Spring Security Log Out Message

free spring framework tutorialSummary

Spring Security is a very popular project in the Spring Framework family of projects. When you need to secure content in a Spring Boot web application, Spring Security is a natural ‘go to’ tool to use.

In this post, I’ve only scratched the surface of the capabilities of Spring Security. For example, I used the in-memory authentication provider for Spring Security. This a great tool to demonstrate how to configure Spring Security. But, you probably would not use an in-memory authentication provider in production. It’s actually fairly common to store user credentials in a database. In the next post of this series, I’ll explain how to setup a DAO authentication provider for Spring Security.

3
Share

Spring Boot – Making Spring Fun Again

I’ve been playing around with Spring Boot again and really like what The Spring Team has been doing. Spring Boot is making Spring fun again. I haven’t had this much pleasure developing Spring Applications since I started learning Grails.

One of the things I loved about the Grails framework was its common sense approach to building web applications. Sure, Spring was under the covers of Grails. But the Grails team wired Spring up with a lot of defaults. For example, if you were using Hibernate to write to a database of course you’re going to want a Spring Transaction Manager.

Grails came out of the box with a transaction manager configured for you. If you were writing a Spring MVC application, you’d need to add a transaction manager into your configuration. The Spring Framework gives you all these pre-built components, but it was left up to you to wire them up into your application. You as the developer are responsible for everything. All the components are there, but some ‘assembly’ is required.

The cool part about Spring Boot is it makes a lot of common sense guesses for you. Like if you add Hibernate to your build, it guesses you’re going to want a transaction manager. The transaction manager is just one example of a common no-brainer Spring component you’d normally need to wire up that Spring Boot will automatically do for you. Spring Boot actually has over 200 default choices which it makes for you.

Spring Boot takes a lot of the mundane pain out of building Spring Applications. It really is making Spring Fun again. Spring Boot is still a newcomer in the family of Spring Projects. Even though Spring Boot is new, I think its the future of Spring application development.

Building a Spring Boot Web Application

Think about building a simple web application using Spring. You’re probably going to want to:

  • Use Spring of course!
  • Spring MVC for the web part.
  • Thymeleaf for the template engine, because you’re just plain tired of using JSPs.
  • Good ol’ Hibernate for your ORM.
  • An H2 database as your development database.
  • Spring Data to take the pain out of using Good Ol’ Hibernate.
  • Spring Security to secure your web application.
  • Tomcat as your application server.

In this Spring Boot tutorial I’m going to walk you through step by step in developing a web application using Spring Boot and the technologies I listed above.

Free Spring Tutorial
New to Spring? Checkout my free Introduction to Spring online course.

Getting Started with Spring Boot

I already created one ‘Getting Started with Spring Boot‘ post, but I’m going to walk through another example here. I want you to be able to follow through this Spring Boot tutorial step by step.

Creating the Spring Boot Project Using IntelliJ

The folks over at JetBrains have added some awesome support for Spring Boot in IntelliJ. This makes it very easy to create a Spring Boot based project using the IntelliJ IDE.

In the following video, I show you how to initialize a Spring Boot project with IntelliJ.

If you don’t have access to IntelliJ, you can always use the Spring Initializr to download a preconfigured Spring Boot project. Be sure to check the following options:

  • Security
  • Thymeleaf
  • Web
  • JPA
  • H2

Reviewing the Spring Initializr Artifacts

The project created by the Spring Initializer is a Maven project and follows the standard Maven directory layout. Below is a screen print from my IntelliJ IDE. There is one application class created for us, an empty properties file, a stub for a JUnit integration test, and the Maven POM file.
spring boot project structure

SpringBootWebApplication.java

The Spring Initializer create us a very basic Spring Boot application class. Technically, this is a Spring Configuration class. The annotation @SpringBootApplication enables the Spring Context and all the startup magic of Spring Boot.

SpringBootWebApplicationTests.java

We’re also give a stub of a JUnit Integration test. Checkout this post if you’d like to learn more about Integration Testing with Spring and JUnit.

pom.xml

Here is the Maven POM file that the Spring Initializer created for us. This was customized for us based on the options we selected in the Spring Initializer. The presence of these dependencies is important because Spring Boot will make decisions on what to create automatically when certain things are found on the classpath. For example, you can see the dependency for the H2 database. Because this exists on the classpath when the application is run, Spring Boot will automatically create a data connection and an embedded H2 database.

Spring Boot Dependencies

What I found interesting about Spring Boot is how it manages dependencies. In the early days of Java development, you as the developer were required to manage all the dependencies. It was a very time consuming task. And led to a lot of errors. If you were using an open source library in your project, it was very easy to forget one of its dependencies, which could lead to runtime errors. In modern Java development this task of dependency management has been delegated to tools such as Maven.

Now when you define a dependency in Maven, Maven checks that artifacts dependencies, each of which can have its own set of dependencies, and so on. You can read more about dependency management in Maven here.

I’m impressed with how the Spring Boot team has leveraged the dependency management features of Maven (and Gradle) for Spring Boot. Prior to Spring Boot, when setting up a Spring Project, you needed to compose the Spring jars needed for your project. This was not always as straight forward as it sounds. The Spring Boot team has basically created Spring Boot POMs with bundled Spring dependencies.

You can use the Maven command of mvn dependency:tree to generate a report on the dependency tree. Running the command on this project produces the following dependency tree.

Here you can see how the top level Spring Boot starter dependencies listed in the Maven POM file call in their respective Spring components. Its a very simple idea, but very useful too. In days past, I can remember whenever starting a new Spring project spending a morning or so mucking around setting up the Maven Dependencies for the Spring components I was using.

Free Introduction to Spring Tutorial

Are you new to the Spring Framework? Checkout my Free Introduction to Spring Online Tutorial.

Conclusion

In this post we’ve taken a look at using the Spring Initializer via IntelliJ to create a Spring Boot Project and examined the project files created by the Spring Initializer.

If you watched the video of me trying to run the Spring Boot application in IntelliJ, you saw the application fail because there were not Thymeleaf templates. In the next post of this tutorial series on Spring Boot, I’ll show you how to setup the Web Assets.

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

The source code for this post is available on github. You can download it here.

Save

0
Share
,

H2 Database Console

Frequently when developing Spring based applications, you will use the H2 in memory database during your development process. Its light, fast, and easy to use. It generally does a great job of emulating other RDBMs which you see more frequently for production use (ie, Oracle, MySQL, Postgres). When developing Spring Applications, its common to use JPA/Hibernate and leverage Hibernate’s schema generation capabilities. With H2, your database is created by Hibernate every time you start the application. Thus, the database is brought up in a known and consistent state. It also allows you to develop and test your JPA mappings.

H2 ships with a web based database console, which you can use while your application is under development. It is a convenient way to view the tables created by Hibernate and run queries against the in memory database.  Here is an example of the H2 database console.

h2 database console

Configuring Spring Boot for the H2 Database Console

H2 Maven Dependency

Spring Boot has great built in support for the H2 database. If you’ve included H2 as an option using the Spring Initializr, the H2 dependency is added to your Maven POM as follows:

This setup works great for running our Spring Boot application with the H2 database out of the box, but if want to enable the use of the H2 database console, we’ll need to change the scope of the Maven from runtime, to compile. This is needed to support the changes we need to make to the Spring Boot configuration. Just remove the scope statement and Maven will change to the default of compile.

The H2 database dependency in your Maven POM should be as follows:

Spring Configuration

Normally, you’d configure the H2 database in the web.xml file as a servlet, but Spring Boot is going to use an embedded instance of Tomcat, so we don’t have access to the web.xml file. Spring Boot does provide us a mechanism to use for declaring servlets via a Spring Boot ServletRegistrationBean.

The following Spring Configuration declares the servlet wrapper for the H2 database console and maps it to the path of /console.

WebConfiguration.java

Note – Be sure to import the proper WebServlet class (from H2).

If you are not using Spring Security with the H2 database console, this is all you need to do. When you run your Spring Boot application, you’ll now be able to access the H2 database console at http://localhost:8080/console.

Free Spring Tutorial
Check out my FREE Introduction to Spring Course!

Spring Security Configuration

If you’ve enabled Spring Security in your Spring Boot application, you will not be able to access the H2 database console. With its default settings under Spring Boot, Spring Security will block access to H2 database console.

To enable access to the H2 database console under Spring Security you need to change three things:

  • Allow all access to the url path /console/*.
  • Disable CRSF (Cross-Site Request Forgery). By default, Spring Security will protect against CRSF attacks.
  • Since the H2 database console runs inside a frame, you need to enable this in in Spring Security.

The following Spring Security Configuration will:

  • Allow all requests to the root url (“/”) (Line 12)
  • Allow all requests to the H2 database console url (“/console/*”) (Line 13)
  • Disable CSRF protection (Line 15)
  • Disable X-Frame-Options in Spring Security (Line 16)

CAUTION: This is not a Spring Security Configuration that you would want to use for a production website. These settings are only to support development of a Spring Boot web application and enable access to the H2 database console. I cannot think of an example where you’d actually want the H2 database console exposed on a production database.

SecurityConfiguration.java

Using the H2 Database Console

Simply start your Spring Boot web application and navigate to the url http://localhost:8080/console and you will see the following logon screen for the H2 database console.

h2 database console logon screen

Spring Boot Default H2 Database Settings

Before you login, be sure you have the proper H2 database settings. I had a hard time finding the default values used by Spring Boot, and had to use Hibernate logging to find out what the JDBC Url was being used by Spring Boot.

Value Setting
Driver Class org.h2.Driver
JDBC URL jdbc:h2:mem:testdb
User Name sa
Password  <blank>

Conclusion

I’ve done a lot of development using the Grails framework. The Grails team added the H2 database console with the release of Grails 2. I quickly fell in love with this feature. Well, maybe not “love”, but it became a feature of Grails I used frequently. When you’re developing an application using Spring / Hibernate (As you are with Grails), you will need to see into the database. The H2 database console is a great tool to have at your disposal.

Maybe we’ll see this as a default option in a future version of Spring Boot. But for now, you’ll need to add the H2 database console yourself. Which you can see isn’t very hard to do.

Free Spring Tutorial
Check out my FREE Introduction to Spring Course!
8
Share