SecurityConfig.java:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

  @Bean
  public PasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder(10, new SecureRandom());
  }

  @Bean
  @Primary
  // Compatible with adding more password encoders in the future
  public PasswordEncoder passwordEncoderDelegate() {
    PasswordEncoder bCryptPasswordEncoder = this.bCryptPasswordEncoder();

    Map<String, PasswordEncoder> encoders = new HashMap<>();
    encoders.put("bcrypt", bCryptPasswordEncoder);

    return new DelegatingPasswordEncoder("bcrypt", encoders);
  }

  @Bean
  public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
    UserDetails user1 = User.builder()
      .username("username")
      .password(passwordEncoder.encode("password"))
      .roles("USER_ROLE")
      .build();
    return new InMemoryUserDetailsManager(user1);
  }

  @Bean
  public SecurityFilterChain basicSecurityFilterChain(HttpSecurity http) throws Exception {
    http
      .csrf(CsrfConfigurer::disable)
      .authorizeHttpRequests(authorize -> {
        authorize
          .requestMatchers(
            "/css/**",
            "/error",
            "/favicon.ico",
            "/public/**",
            "/webjars/**"
          )
            .permitAll()
          .anyRequest()
            .authenticated();
    })
    // Simplest case:
    // .httpBasic(withDefaults());
    .httpBasic(httpBasic -> httpBasic
      .realmName("Access to Web and API protected resources")
    );
    return http.build();
  }

}


Usage

  • Unhappy Path
curl -v  http://localhost:8080/api/sample
...
> GET /api/samples HTTP/1.1
...
< HTTP/1.1 401
< WWW-Authenticate: Basic realm="Access to Web and API protected resources via Basic Auth"
...
  • Happy Path
curl -v -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" http://localhost:8080/api/samples
...
> GET /api/samples HTTP/1.1
> Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
...
< HTTP/1.1 200
...
["Sample 1","Sample 2","Sample 3","Sample 4"]


HTTP Basic Authentication Scheme Sequence Flow HTTP Basic Authentication Scheme Sequence Flow