Using the H2 Database Console in Spring Boot with Spring Security
44 CommentsLast 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.
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 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.
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.
Daniel
Thanks a lot! I want it.
Daniel
Thank you a lot!
Can I convert to korean?
jt
Sure – I’d appreciate it if you link back to the source! Thanks!
Daniel
Thank you! I will link after finish.
Dirk Hesse
Intellij has a tool/window for that. You can check your database right from the IDE. But nice blogpost anyway. Thx for that.
Daniel
I did translate to korean.
This is post link : http://lahuman.jabsiri.co.kr/128
Thank you for John Thompson.
jt
Thanks Daniel – Can’t read any of it! LOL
Mykhaylo K
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;
}
});
jt
Thanks!
zhuguowei
Thanks! Very useful for me!
zhuguowei
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
jt
Thanks. I saw the Spring Boot team added that. Spring Boot is still evolving quickly!
Thangavel L Nathan
Hello Guru,
Thank you so much, this saved me more time. Keep on posting more blog!
edwardbeckett
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…
}
edwardbeckett
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;
}
Lefteris Kororos
Very nice. I noticed that the default JDBC URL was jdbc:h2:~/test and this seems to work fine.
Chrs
how would you enable remote access to the H2 console usnig application.properties properties
Mir Md. Asif
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.
Robert
THX! Worked perfectly via application.properties
Pradipta Maitra
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.
jt
Sorry – I’m not familiar with Bluemix.
If you figure it out, please post the solution here for others!
Bryan Beege Berry
I had to add the following dependency:
“`
org.springframework.security
spring-security-config
4.2.0.RELEASE
“`
Ahmet Ozer
Thank you very much.
kay
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
Hemanshu
For my spring boot application, adding below to application.properties is not working. Any idea why ?
security.headers.frame=false
Riley
Spring Boot 2.0.0 ==> org.springframework.boot.web.servlet.ServletRegistrationBean
Felix
Hi,
looks like the ServletRegistrationBean is no longer available with version 2.0.0.RELEASE.
Is there an alternativ?
Aleks
Hi !
Thank you !
I adopted your advice to my code and surprisingly it worked !
Eduardo
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!
Matthew Weiler
Thank you,
This is just what I needed when I just want to work with a quick-and-dirty H2 database while developing.
Krzysztof Fitas
Nicely done
Mithil Wane
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.