web-dev-qa-db-ja.com

Springセキュリティを備えた特定のエンドポイントにHTTP基本認証を追加するにはどうすればよいですか?

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)

これらのリソースは役に立ちましたが、十分ではありませんでした:

13
dave

ここで説明するように、解決策は複数の構成を実装することです: https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity

5
dave
@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
pvpkiran