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

时间:2016-07-15 19:25:23

标签: 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");
    }
}

1 个答案:

答案 0 :(得分:6)

默认情况下,当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");
    }

}