,

Using the H2 Database Console in Spring Boot with Spring Security

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!
Share

You May Also Like

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

  1. Thanks a lot! I want it.

  2. Thank you a lot!
    Can I convert to korean?

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

      • Thank you! I will link after finish.

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

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

    Thank you for John Thompson.

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

  5. 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;
    }
    });

    • Thanks!

  6. Thanks! Very useful for me!

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

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

  8. Hello Guru,

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

  9. 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…
    }

  10. 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;
    }

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

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

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

    • THX! Worked perfectly via application.properties

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

    • Sorry – I’m not familiar with Bluemix.

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

  15. I had to add the following dependency:

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

  16. Thank you very much.

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

Leave a Reply