A simple secure spring web application needs a database to be configures at its backend. This post covers how to configure h2 db and access its console.
To add H2 in spring boot application, you need to add following maven dependency in pom.xml
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
Spring boot will automatically configure it when it sees its dependency on classpath.
You need to add the following bean.
@Configuration
public class H2Config {
@Bean
ServletRegistrationBean h2servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
}
That’s it, fire up your application and try hitting URL: http://localhost:8080/console/
It will prompt for username and password, which will be
username : user
password: <check for log line, “Using default security password: 3cbb1572-36c6-4487-b602-11ab2dc576ad”>
Add the following security configuration
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests().antMatchers("/console/**").permitAll()
.anyRequest().authenticated();
httpSecurity.csrf().disable();
httpSecurity.headers().frameOptions().disable();
}
}
You’re good to go.
To access the full working code sample, click here
Settings dialog