Add H2 Database to Spring Boot Project with Spring Security

In this tutorial, I am going to share with you how to add H2 In-memory database support to your Spring Boot project which has Spring Security enabled. And at the end of this tutorial, you will find a video demonstration of how to do it.

Once you do the below-described steps, your Spring Boot project will be using the H2 In-Memory database instead of another database which you have configured for your project if any. And all the data will be recorded into database tables which will have the same structure but will be kept in memory which means that if you restart or shutdown your Spring Boot project, the data kept in-memory database tables will be erased.

Add H2 In-Memory Database POM.xml Dependency

Open the POM.xml file of your Spring Boot project and add the following dependency:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

Update the application.properties File

1. Add the spring.h2.console.enabled=true to application.properties file

For you to be able to use the H2 In-Memory Database console and be able to view the database tables content, you should enable the h2-console in your application.properties file.

Add the following line to your application.properties file:

spring.h2.console.enabled=true

2. Comment out other database connection details

If you have other database connection details in your properties file, please comment it out just to make sure there is no conflict. For example, in my application.properties file, I have connection details for MySQL database. I needed to comment those out.

#spring.datasource.url=jdbc:mysql://localhost:3306/photo_app
#spring.datasource.username=sergey
#spring.datasource.password=sergey
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
server.servlet.context-path=/mobile-app-ws
 
spring.h2.console.enabled=true
 
 

Update WebSecurity Java Class

Disable the frameOptions()

If your Spring Boot project is using Spring Security then most likely you have a class which extends the WebSecurityConfigurerAdapter. In the configure() method of that class add the following like to disable the HTTP Header Frame Options. Frame options are needed to prevent a browser to load your HTML page in an <iframe> or a <frame> tag and for H2 Console page to load, you need to disable this option.

http.headers().frameOptions().disable();

Allow access to /h2-console URL path

Additionaly to disabling the frameOptions in your configure method, you will need to allow the access to /h2-console path. You can do it by adding the following to your HttpSecurity:

antMatchers("/h2-console/**")
                .permitAll()

Here is my complete configure() function which is to configure the HttpSecurity. Notice how I granted access to a /h2-console

@Override
   protected void configure(HttpSecurity http) throws Exception {

       http.csrf().disable().
               authorizeRequests()
               .antMatchers(HttpMethod.POST, SecurityConstants.SIGN_UP_URL)
               .permitAll()
               .antMatchers(HttpMethod.GET, SecurityConstants.VERIFICATION_EMAIL_URL)
               .permitAll()
               .antMatchers(HttpMethod.POST, SecurityConstants.PASSWORD_RESET_REQUEST_URL)
               .permitAll()         
               .antMatchers(HttpMethod.POST, SecurityConstants.PASSWORD_RESET_URL)
               .permitAll() 
               .antMatchers("/h2-console/**")
               .permitAll()
               .anyRequest().authenticated().and()
               .addFilter( new AuthenticationFilter(authenticationManager()) )
               //.addFilter(getJWTAuthenticationFilter()) // To create a custom URL for authenticaiton filter
               .addFilter( new AuthorizationFilter( authenticationManager() ))
               .sessionManagement()
               .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
       
       http.headers().frameOptions().disable();
   }

And this is it.

Now you should be able to:

  1. Build + Run your Spring Boot application,
  2. In your Browser window open the http://localhost:8080/<application context>/h2-console URL and you should be able to see the login page like the one below. Please notice the <application context> in my URL. Provide the application context only if you have set it in application.properties file like this:
server.servlet.context-path=/MyProjectName

Otherwise skip it and access the h2-console this way: http://localhost:8080/h2-console.

H2 Console Login page

Once you have done the above-described steps, you should be able to see the following login page:

Simply click on Connect to sign in to your H2 Console and start working with H2 In-Memory Database.

Video Demonstration

More videos you can find here: RESTful Web Services, Java, Spring Boot, Spring MVC and JPA

If you are looking to learn even more about Spring Boot, check out the below list of Video Courses and hopefully one of them will be useful to you.