Spring Security for h2-console

In Spring Boot example apps, H2 is the easiest database to get started with. Its data is in memory or in a local file. When the app is running in development mode, you can access the database at /h2-console. It gives you a lovely little SQL admin app.

screenshot of the console

That is, after you turn it on in application.properties:


When you bring in Spring Security, though, that console stops working.

First it’s all “Unauthorized!” and then once I get past that, and log in to the console itself, I get four frames of “NOPE.”

screenshot of the console's attempt to display four frames which refuse to load

Here is the spell to make /h2-console work again. Cast it in your security configuration, in your class that extends WebSecurityConfigurerAdapter.

protected void configure(HttpSecurity http) throws Exception {
// ... your other configuration

This takes /h2-console out of Spring Security’s authorization, so you don’t have to log in to the app before you can log in to the database.

Then it turns off CSRF only for /h2-console. CSRF protection breaks all POSTs until you add the secret formula to each form. The console doesn’t have these, so it is not compatible with CSRF protection.

Then it enables loading pages in frames as long as the frames come from our own site. This affects the entire application. (I don’t know how to configure the headers for only /h2-console.)

Now the console will work when you’re running your app locally, and the rest of your site will be secure as before.