Spring JDBC Authentication


Spring JDBC Authentication

In Authentication with a Database-backed UserDetailsService post, we analyzed one approach to achieve this by implementing the UserDetailService interface ourselves.

In this regard, we will use the instructions of AuthenticationManagerBuilder #jdbcAuthentication to analyze the pros and cons of this more direct approach.

Using embedded H2 Connection

First, we will analyze how we can achieve Authentication using an embedded H2 database. This is easy to accomplish because Spring Boot's autoconfiguration is prepared out-of-the-box for this scenario.

Let's start by following the instructions of Spring Boot With H2 Database post to:

Include the corresponding spring-boot-starter-data-jpa and h2 dependencies

Configure the database connection with application properties

Enable the H2 console

Configuring JDBC Authentication

@Autowired private DataSource dataSource; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth)   throws Exception {     auth.jdbcAuthentication()       .dataSource(dataSource)       .withDefaultSchema()       .withUser(User.withUsername("user")         .password(passwordEncoder().encode("pass"))         .roles("USER")); } @Bean public PasswordEncoder passwordEncoder() {     return new BCryptPasswordEncoder(); }

  We can see, we're using the autoconfigured DataSource. The withDefaultSchema directive adds a database script that will populate the default schema, allowing users and authorities to be stored. This basic user schema is documented in the Spring Security Appendix.

Finally, we will be creating an entry in the database with a default user programmatically.

Verifying the Configuration

@RestController @RequestMapping("/principal") public class UserController {     @GetMapping     public Principal retrievePrincipal(Principal principal) {         return principal;     } }

In addition, we'll secure this endpoint, whilst permitting access to the H2 console:

@Configuration public class SecurityConfiguration   extends WebSecurityConfigurerAdapter {     @Override     protected void configure(HttpSecurity httpSecurity)       throws Exception {         httpSecurity.authorizeRequests()           .antMatchers("/h2-console/**")           .permitAll()           .anyRequest()           .authenticated()           .and()           .formLogin();                  httpSecurity.csrf()           .ignoringAntMatchers("/h2-console/**");         httpSecurity.headers()           .frameOptions()           .sameOrigin();     } }