Using the H2 Database Console in Spring Boot with Spring Security

Using the H2 Database Console in Spring Boot with Spring Security

44 Comments

Last Updated on June 5, 2019 by Michelle Mesiona

H2 Database Console

Frequently when developing Spring based applications, you will use the H2 in memory database during your development process. It’s 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:

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

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:

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

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).

import org.h2.server.web.WebServlet;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebConfiguration {
    @Bean
    ServletRegistrationBean h2servletRegistration(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
        registrationBean.addUrlMappings("/console/*");
        return registrationBean;
    }
}

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.

Spring Framework 5
Click here to learn about my Spring Framework 5: Beginner to Guru online 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

package guru.springframework.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().antMatchers("/").permitAll().and()
                .authorizeRequests().antMatchers("/console/**").permitAll();

        httpSecurity.csrf().disable();
        httpSecurity.headers().frameOptions().disable();
    }

}

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.

ValueSetting
Driver Classorg.h2.Driver
JDBC URLjdbc:h2:mem:testdb
User Namesa
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.

Spring Framework 5
Become a Spring Framework Guru with my online course Spring Framework 5: Beginner to Guru!

 

About jt

    You May Also Like

    44 comments on “Using the H2 Database Console in Spring Boot with Spring Security

    1. August 25, 2015 at 6:15 am

      Thanks a lot! I want it.

      Reply
    2. August 25, 2015 at 8:01 am

      Thank you a lot!
      Can I convert to korean?

      Reply
      • August 25, 2015 at 8:21 am

        Sure – I’d appreciate it if you link back to the source! Thanks!

        Reply
        • August 25, 2015 at 9:19 am

          Thank you! I will link after finish.

          Reply
    3. August 25, 2015 at 2:34 pm

      Intellij has a tool/window for that. You can check your database right from the IDE. But nice blogpost anyway. Thx for that.

      Reply
    4. August 26, 2015 at 5:21 am

      I did translate to korean.
      This is post link : http://lahuman.jabsiri.co.kr/128

      Thank you for John Thompson.

      Reply
      • August 26, 2015 at 6:18 am

        Thanks Daniel – Can’t read any of it! LOL

        Reply
    5. September 3, 2015 at 5:22 am

      Thank you for this post. Quite useful. Just want to add, maybe somebody find it useful. If you don’t want to disable CSRF protection for whole application but for H2 console only, you can use this configuration:

      httpSecurity.csrf().requireCsrfProtectionMatcher(new RequestMatcher() {
      private Pattern allowedMethods = Pattern.compile(“^(GET|HEAD|TRACE|OPTIONS)$”);
      private RegexRequestMatcher apiMatcher = new RegexRequestMatcher(“/console/.*”, null);

      @Override
      public boolean matches(HttpServletRequest request) {
      if(allowedMethods.matcher(request.getMethod()).matches())
      return false;
      if(apiMatcher.matches(request))
      return false;
      return true;
      }
      });

      Reply
      • September 3, 2015 at 6:45 am

        Thanks!

        Reply
    6. October 17, 2015 at 11:44 pm

      Thanks! Very useful for me!

      Reply
    7. October 18, 2015 at 12:13 am

      Hei,
      Just now, I found a more convenient solution to access h2 web console, this time you need do nothing. It’s out of box.
      As of Spring Boot 1.3.0.M3, the H2 console can be auto-configured.

      The prerequisites are:

      You are developing a web app
      Spring Boot Dev Tools are enabled
      H2 is on the classpath
      Check out this part of the documentation for all the details.

      I see it from http://stackoverflow.com/questions/24655684/spring-boot-default-h2-jdbc-connection-and-h2-console

      Reply
      • October 19, 2015 at 9:36 am

        Thanks. I saw the Spring Boot team added that. Spring Boot is still evolving quickly!

        Reply
    8. December 6, 2015 at 12:28 am

      Hello Guru,

      Thank you so much, this saved me more time. Keep on posting more blog!

      Reply
    9. December 13, 2015 at 6:00 am

      I modified a config to implement starting up an h2TCP connection for the servlet… it’s pretty handy when working within IntelliJ 😉

      public class AppConfig implements ServletContextInitializer, EmbeddedServletContainerCustomizer {

      @Inject
      private Environment env;

      private RelaxedPropertyResolver propertyResolver;

      @PostConstruct
      public void init() {
      this.propertyResolver = new RelaxedPropertyResolver( env, “spring.server.” );
      }

      @Override
      public void onStartup( ServletContext servletContext ) throws ServletException {
      log.info( “Web application configuration, using profiles: {}”,
      Arrays.toString( env.getActiveProfiles() ) );
      EnumSet disps = EnumSet.of( DispatcherType.REQUEST, DispatcherType.FORWARD,
      DispatcherType.ASYNC );
      initH2TCPServer( servletContext );
      initLogBack( servletContext );
      log.info( “Web application fully configured” );
      }

      //Other methods elided…

      /**
      * Initializes H2 console
      */
      public void initH2Console( ServletContext servletContext ) {
      log.debug( “Initialize H2 console” );
      ServletRegistration.Dynamic h2ConsoleServlet = servletContext.addServlet( “H2Console”,
      new org.h2.server.web.WebServlet() );
      h2ConsoleServlet.addMapping( “/console/*” );
      h2ConsoleServlet.setInitParameter( “-properties”, “src/main/resources” );
      h2ConsoleServlet.setLoadOnStartup( 3 );

      }

      //more methods elided…
      }

      Reply
    10. December 13, 2015 at 6:03 am

      Continued… ( hit submit too early 😉 )

      /**
      * Initializes H2 TCP Server…
      *
      * @param servletContext
      *
      * @return
      */
      @Bean( initMethod = “start”, destroyMethod = “stop” )
      public Server initH2TCPServer( ServletContext servletContext ) {
      try {
      if( propertyResolver.getProperty( “tcp” ) != null && “true”.equals(
      propertyResolver.getProperty( “tcp” ) ) ) {
      log.debug( “Initializing H2 TCP Server” );
      server = Server.createTcpServer( “-tcp”, “-tcpAllowOthers”, “-tcpPort”, “9092” );
      }
      } catch( SQLException e ) {
      e.printStackTrace();
      } finally {
      //Always return the H2Console…
      initH2Console( servletContext );
      }
      return server;
      }

      Reply
    11. December 30, 2015 at 3:25 pm

      Very nice. I noticed that the default JDBC URL was jdbc:h2:~/test and this seems to work fine.

      Reply
    12. May 18, 2016 at 3:52 am

      how would you enable remote access to the H2 console usnig application.properties properties

      Reply
    13. June 16, 2016 at 6:24 am

      Since Spring Boot 1.3.0 just adding this two property in application.properties is enough.

      spring.h2.console.enabled=true
      spring.h2.console.path=/console

      H2ConsoleAutoConfiguration will take care of the rest.

      Reply
      • January 2, 2017 at 6:16 pm

        THX! Worked perfectly via application.properties

        Reply
    14. October 19, 2016 at 7:48 am

      I had deployed this app both in local box and also in IBM Bluemix. On the local box, even without the SecurityConfiguration (however with the WebConfiguration) I was able to view the H2 Console. However, in bluemix, I was not able to view the H2 console and it gave me the error “Sorry, remote connections (‘webAllowOthers’) are disabled on this server”.

      Will you be able to help me in this regard, by pointing out what I might be missing.

      Reply
      • October 19, 2016 at 8:58 am

        Sorry – I’m not familiar with Bluemix.

        If you figure it out, please post the solution here for others!

        Reply
    15. November 18, 2016 at 2:48 am

      I had to add the following dependency:
      “`

      org.springframework.security
      spring-security-config
      4.2.0.RELEASE

      “`

      Reply
    16. November 28, 2016 at 10:05 am

      Thank you very much.

      Reply
    17. May 19, 2017 at 9:12 pm

      FYI, I have updated
      import org.springframework.boot.context.embedded.ServletRegistrationBean;
      to
      import org.springframework.boot.web.servlet.ServletRegistrationBean;

      in order to run in the latest springboot

      Reply
    18. August 9, 2017 at 9:15 am

      For my spring boot application, adding below to application.properties is not working. Any idea why ?
      security.headers.frame=false

      Reply
    19. January 6, 2018 at 9:25 pm

      Spring Boot 2.0.0 ==> org.springframework.boot.web.servlet.ServletRegistrationBean

      Reply
    20. April 4, 2018 at 6:15 am

      Hi,
      looks like the ServletRegistrationBean is no longer available with version 2.0.0.RELEASE.
      Is there an alternativ?

      Reply
    21. September 6, 2019 at 12:36 pm

      Hi !
      Thank you !
      I adopted your advice to my code and surprisingly it worked !

      Reply
    22. April 11, 2020 at 12:57 pm

      The csrf was getting me! I just forgot about it and was having a hard time do find why i was getting 403 to access the database. Thanks!

      Reply
    23. April 30, 2020 at 1:55 pm

      Thank you,

      This is just what I needed when I just want to work with a quick-and-dirty H2 database while developing.

      Reply
    24. June 24, 2021 at 7:53 am

      Nicely done

      Reply
    25. September 18, 2023 at 10:10 am

      Any Idea how would I be able to set this inside a webconfig instead of using the property to enable it. While using Spring Boot.

      Reply

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.