spring security - basic auth

PHOTO EMBED

Mon Mar 15 2021 17:15:39 GMT+0000 (Coordinated Universal Time)

Saved by @edwgarci #spring #security

// open api
@SecurityScheme(
    name = "Basic Auth",
    type = SecuritySchemeType.HTTP,
    scheme = "basic",
    description = "Basic Auth")

// security config 2 users
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/api/**")
        .authorizeRequests()
        .anyRequest()
        .authenticated()
        .and()
        .httpBasic()
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .exceptionHandling()
        .authenticationEntryPoint(new Http403ForbiddenEntryPoint())
        .and()
        .csrf()
        .disable();
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
        .passwordEncoder(new BCryptPasswordEncoder())
        .withUser("<username>")
        .password(passwordEncoder().encode("<password>"))
        .roles("<role>")
        .and()
        .withUser("<user2>")
        .password(passwordEncoder().encode("<password2>"))
        .roles("<role>");
  }

// controllers
@SecurityRequirement(name = "Basic Auth")
content_copyCOPY

Adding basic authentication