Add H2 Database to Spring Boot Project with Spring Security

In this tutorial, I will share 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 steps below, your Spring Boot project will use the H2 In-Memory database. All the data will be recorded into the database and kept in memory, which means that if you restart or shut down your Spring Boot application, 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

To be able to use the H2 In-Memory Database console and 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, to ensure there is no conflict. For example, in my application.properties file, I have connection details for the MySQL database. I needed to comment out the following properties

#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, you likely have a class that extends the WebSecurityConfigurerAdapter. In that class’s configure() method, add the following to disable the HTTP Header Frame Options. Frame options are needed to prevent a browser from loading your HTML page in an <iframe> or a <frame> tag, and for the H2 Console page to load, you need to disable this option.

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

Allow access to /h2-console URL path

Additionally, you will need to allow access to the /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 the 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:

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

Database “mem:testdb” not found, either pre-create it or allow remote database creation

If, for some reason, you are getting the following error message when trying to log-in “Database “mem:testdb” not found, either pre-create it or allow remote database creation“, then configure the H2 database access details in the application.properties file.

spring.h2.console.enabled=true
spring.datasource.username=sergey
spring.datasource.password=sergey
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

This should resolve the issue.

Video Demonstration

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

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


Leave a Reply

Your email address will not be published.