Spring Securityを備えたSpring Bootアプリケーションがあります。新しいエンドポイント/health
を設定して、基本的なHTTP認証を介してアクセスできるようにします。現在のHttpSecurity
構成は次のとおりです。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers(HttpMethod.OPTIONS, "/**")
.and()
.csrf()
.disable()
.authorizeRequests()
.anyRequest()
.permitAll()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
/health
の基本認証を追加するにはどうすればよいですか?私はこのようなものが必要だと思っていますが、これは完全に正しいとは思いません。正確にどこに追加するのか本当にわかりません。
.authorizeRequests()
.antMatchers(
// Health status
"/health",
"/health/"
)
.hasRole(HEALTH_CHECK_ROLE)
.and()
.httpBasic()
.realmName(REALM_NAME)
.authenticationEntryPoint(getBasicAuthEntryPoint())
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
これらのリソースは役に立ちましたが、十分ではありませんでした:
ここで説明するように、解決策は複数の構成を実装することです: https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity
@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")
;
}
}