仅验证选定的休息端点:弹簧引导

Kal*_*ava 6 java spring spring-security spring-boot

我有一个Spring Boot Web应用程序,暴露了很少的休息端点.我想知道我们如何只为选定的休息端点启用基本身份验证.假设我只/employee/{id}想要进行身份验证请求并忽略所有其他其他端点.我使用以下代码.我的问题是antMatcher唯一验证指定的请求吗?目前,它为所有其他端点启用身份验证:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
         // How does it work will it only authenticate employee & 
         // ignore any other request?? Its authenticating all the requests currently. 
         http
            .authorizeRequests()
                 .antMatchers("/employee/*").authenticated()
            .and()
            .httpBasic()
            .and()
            .csrf()
                .disable();    
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("admin").password("admin").roles("USER");
    }
}
Run Code Online (Sandbox Code Playgroud)

Kyl*_*son 8

默认情况下,当Spring Security位于类路径上时,Spring Boot将保护所有端点.

您需要为所有其他端点显式添加排除项,而无需身份验证.

例:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
               .antMatchers("/employee/*").authenticated()
               .anyRequest().permitAll()
             .and()
             .httpBasic()
             .and()
             .csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("admin").password("admin").roles("USER");
    }

}
Run Code Online (Sandbox Code Playgroud)