java - 仅验证选定的其余端点 : spring boot

标签 java spring spring-security spring-boot

我有一个 Spring Boot Web 应用程序,它公开了几个 rest 端点。我想知道我们如何才能只为选定的其余端点启用基本身份验证。假设我只想对 /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");
    }
}

最佳答案

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

}

关于java - 仅验证选定的其余端点 : spring boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38403740/

相关文章:

java - OpenID Connect 的 Spring Security 5 XML 配置

java - 如何在一个框架中添加绘图(绘画方法)和另一个带有控件的面板?

spring - Grails Spring Core 安全插件 - 无法解析类

java - Spring 中完整的 AspectJ 支持

java - 将 Spring MVC 的 Controller 与 HTTPServlet 解耦

grails - 发生故障时如何使用Spring Security Core插件获取登录尝试

Spring Security 4 自定义登录 j_spring_security_check 返回 http 302

java - 如何在 Java 守护进程中捕获 linux 用户注销信号?

java - 将 arrayCollection 从 flex 传递到 java

java - 如何创建 ArrayList 的安全保存并在类被编辑时加载它?