Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add HTTP basic auth for a specific endpoint with spring security?

I have a Spring Boot application with Spring Security. A new endpoint /health is to be configured so it is accessible via basic HTTP authentication. The current HttpSecurity configuration is as follows:

@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 base auth for /health? I figure I need something like this, but I don't think this is completely correct, and I don't really 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 to be helpful, but not sufficient:

  • http://www.baeldung.com/spring-security-basic-authentication
  • http://websystique.com/spring-security/secure-spring-rest-api-using-basic-authentication/
like image 472
dave Avatar asked Apr 20 '17 15:04

dave


1 Answers

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

EDIT 2021-12-11:

archive link of reference: https://web.archive.org/web/20210126145444/https://docs.spring.io/spring-security/site/docs/current/reference/html5/#multiple-httpsecurity

A similar question linking to an example is here: https://stackoverflow.com/a/18864786/1568224

like image 181
dave Avatar answered Nov 16 '22 11:11

dave