Let's Build an API Together - Part 24

Last Update: 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:

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

    private AppUserDetailsService appUserDetailsService;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    protected void configure(HttpSecurity http) throws Exception {
        .antMatchers("/register", "/h2-console/**").permitAll()

    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.

Want content like this in your inbox each workday irregularly? No BS, spam or tricks... just useful content:

I understand and agree to the privacy policy