问题
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/
回答1:
The solution is to implement multiple configurations, as explained here: https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity
回答2:
@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")
;
}
}
来源:https://stackoverflow.com/questions/43524211/how-do-i-add-http-basic-auth-for-a-specific-endpoint-with-spring-security