【问题标题】:Authenticate only selected rest end points : spring boot仅验证选定的休息端点:弹簧靴
【发布时间】:2016-11-19 02:44:42
【问题描述】:

我有一个 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");
    }
}

【问题讨论】:

  • 您的配置对我来说似乎很好。确定正在应用此配置吗?您是否在控制台上看到默认 user 的随机密码?请发布您的项目结构。

标签: java spring spring-security spring-boot


【解决方案1】:

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

}

【讨论】:

    猜你喜欢
    • 2020-03-12
    • 2018-07-22
    • 2019-06-24
    • 2017-12-22
    • 2016-07-14
    • 2018-02-14
    • 1970-01-01
    • 2017-12-18
    • 2019-05-03
    相关资源
    最近更新 更多