How to add HTTP basic authentication for a specific endpoint using spring security?

I have a Spring Boot Application with Spring Security. The new endpoint /health

must be configured to be accessible through HTTP Basic Authentication. The current configuration HttpSecurity

looks like this:

@Override
protected void configure(HttpSecurity http) throws Exception {

http.requestMatchers()
    .antMatchers(HttpMethod.OPTIONS, "/**")
    .and()
    .csrf()
    .disable()
    .authorizeRequests()
    .anyRequest()
    .permitAll()
    .and()
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

      

}

How do I add basic auth for /health

? I suppose I need something like this, but I don't think it's absolutely correct and I don't understand where exactly to add it:

    .authorizeRequests()
    .antMatchers(
        // Health status
        "/health",
        "/health/"
    )
    .hasRole(HEALTH_CHECK_ROLE)
    .and()
    .httpBasic()
    .realmName(REALM_NAME)
    .authenticationEntryPoint(getBasicAuthEntryPoint())
    .and()
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

      

I found these resources useful, but not sufficient:

+3


source to share


2 answers


The solution is to implement multiple configurations as described here: https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity



+3


source


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/health/**").hasRole("SOME_ROLE")
            .anyRequest().authenticated()
            .and()
            .httpBasic()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {


        auth
            .inMemoryAuthentication()
            .withUser("yourusername").password("yourpassword").roles("SOME_ROLE")

        ;
    }

}

      



0


source







All Articles