Over a million developers have joined DZone.

Auto-Generating Spring Security: Accessing the In-memory Database

Here's a nice Spring Security + Spring Boot tutorial on using in-memory H2 Database to configure Spring Security with source code examples.

· Database Zone

Build fast, scale big with MongoDB Atlas, a hosted service for the leading NoSQL database. Try it now! Brought to you in partnership with MongoDB.

I came across a blog post from the Spring Framework Guru that uses the H2 database console, and I thought it would be useful to combine the console with my own Spring Security tutorials.

I’ve updated the parkrunpb project on GitHub to replace hsqldb with h2database. I've also introduced a new class — WebConfiguration.java — which registers the H2 database servlet.

First, let's start the application:

mvn spring-boot:run

Access the Console

You can access the console through -http://localhost:8080/console. 

console2

You then make sure the JDBC URL is:

jdbc:h2:mem:testdb

And login:

console3

The layout shows the tables we loaded in schema.sql on the right (CUSTOM_AUTHORITIES, CUSTOM_USERS, and PARKRUNCOURSE)

Combine it With Spring Security

The next step is to combine with Spring Security, so I’ll use the configuration from the previous tutorial — Auto-generating Spring Security Tutorial – Custom JDBC Realms

We start with our class:

@EnableWebSecurity public class SecurityConfig extends 
  WebSecurityConfigurerAdapter {     
  @Autowired     
  private DataSource dataSource;     
  @Autowired     
  public void configureGlobal(AuthenticationManagerBuilder auth)             
    throws Exception {          
    auth              
      .jdbcAuthentication()                  
      .dataSource(dataSource)                    
      .usersByUsernameQuery(                    
      "select username, password, enabled from custom_users where username = ?")
      .authoritiesByUsernameQuery(                    
      "select username, authority from custom_authorities where username = ?");  
  }    
  @Override    
  protected void configure(HttpSecurity http) throws Exception {         
    http             
      .authorizeRequests()                 
      .antMatchers("/webjars/**","/about.html","/rest/**").permitAll()     
      .antMatchers("/admin/**").hasAnyRole("CUSTOM_ADMIN")                 
      .anyRequest().authenticated()             
      .and()                 
      .formLogin()                     
      .loginPage("/login")                     
      .defaultSuccessUrl("/admin/admin.html")                     
      .failureUrl("/login")                     
      .permitAll()              
      .and()                 
      .logout()                     
      .logoutSuccessUrl("/")                     
      .permitAll()                     ;                         
  }     
}


We then add to the configure method:

http.authorizeRequests().antMatchers("/").permitAll().and()                 
  .authorizeRequests().antMatchers("/console/**").permitAll();          
http.csrf().disable();         
http.headers().frameOptions().disable();


The method then becomes:

@Override     
protected void configure(HttpSecurity http) throws Exception {         
  http             
    .authorizeRequests()                 
    .antMatchers("/webjars/**","/about.html","/rest/**").permitAll()    
    .antMatchers("/admin/**").hasAnyRole("CUSTOM_ADMIN")                 
    .anyRequest().authenticated()             
    .and()                 
    .formLogin()                     
    .loginPage("/login")                     
    .defaultSuccessUrl("/admin/admin.html")                     
    .failureUrl("/login")                     
    .permitAll()              
    .and()                 
    .logout()                     
    .logoutSuccessUrl("/")                     
    .permitAll();                              
  http.authorizeRequests().antMatchers("/").permitAll().and()                 
    .authorizeRequests().antMatchers("/console/**").permitAll();          
  http.csrf().disable();         
  http.headers().frameOptions().disable();                          
}

This means the normal security from the original tutorial is applied to the application, but we have a special rule for the console.

You can then test the application as before with the username/password customadmin/customadmin. You could also insert or update courses.

Now it's easier than ever to get started with MongoDB, the database that allows startups and enterprises alike to rapidly build planet-scale apps. Introducing MongoDB Atlas, the official hosted service for the database on AWS. Try it now! Brought to you in partnership with MongoDB.

Topics:
in-memory ,spring boot ,database ,spring security

Published at DZone with permission of Martin Farrell, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}