Want to improve as a dev?

I send a short email every workday about Spring topics, API development and improving as a dev.

I understand and agree to the privacy policy

Let's Build an API Together - Part 24

30.01.2018 by Jens in API Series | APIs | Newsletter

Now, we are ready to set up the user and configure Spring Security to protect our API.

The user is just a simple @Entity with an id, username and a password. We also create a UserRepository with a method to query by username like User findByUsername(String username);.

The key element for integration with Spring Security is we need to provide a UserDetailsService so it will use our Spring Data repository for finding users.

Next, we configure Spring Security by adding a new configuration class:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AppUserDetailsService appUserDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(appUserDetailsService).passwordEncoder(encoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/register", "/h2-console/**").permitAll()
        .anyRequest().authenticated()
        .and().headers().frameOptions().disable()
        .and().httpBasic();
    }

    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }
}

WebSecurityConfigurerAdapter is a convenient class to override Spring Security configs. AppUserDetailsService is the UserDetailsService I created. Using the AuthenticationManagerBuilder we configure Spring Security to use our UserDetailsService implementation and also define a password encoder. We do not store plain text in the DB. BCryptPasswordEncoder uses salting and hashing.

register and /h2-console are open to anyone. The rest of the API is protected. We also allow basic auth and disable any csrf because we do not need it.

Next time we implement the login and register workflows.


comments powered by Disqus