【问题标题】:Spring Boot 2.0 disable default securitySpring Boot 2.0 禁用默认安全性
【发布时间】:2018-04-26 16:30:32
【问题描述】:

我想使用 Spring Security 进行 JWT 身份验证。但它带有默认身份验证。我正在尝试禁用它,但这样做的旧方法 - 通过application.properties 禁用它 - 在 2.0 中已弃用。

这是我尝试过的:

@Configuration
public class StackWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().disable();
        // http.authorizeRequests().anyRequest().permitAll(); // Also doesn't work.
    }
}

我怎样才能简单地禁用基本安全性?

更新
很高兴知道我使用的不是 web mvc 而是 web Flux。

截图:

【问题讨论】:

  • 您是否尝试排除包,如您所见here
  • @Y.Colin 是的,我试过了。我只能通过删除整个依赖项来禁用它..
  • 您能再解释一下吗?现在有什么是以前没有的?你的安全配置是什么?你能提供一个请求+响应的例子吗?
  • @BrianClozel 目前它只是一个空应用程序,我只想在没有基本身份验证的情况下使用 Spring Security。您可以通过创建一个 Spring Boot 2.0 Web 应用程序并使用 @EnableWebFlux 来复制它。
  • 添加 @EnableWebFlux 会有效地禁用所有 WebFlux 自动配置。你打算这样做吗?

标签: spring-boot spring-security spring-webflux spring-security-rest


【解决方案1】:

根据 Spring 2.0 中的新更新,如果 Spring Security 在 classpath 上,Spring Boot 将添加 @EnableWebSecurity。所以向 application.properties 添加条目是行不通的(即它不再是可定制的) .更多信息请访问官网Security changes in Spring Boot 2.0

虽然不确定您的具体要求,但我可以想到一种解决方法,如下所示:-

@Configuration
@EnableWebSecurity
public class SecurityConfiguration  extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests().antMatchers("/").permitAll();
    }
}

希望这会有所帮助。

【讨论】:

  • 这个问题是关于在Spring Boot中为Spring WebFlux配置安全性; @EnableWebSecurity 用于 Spring MVC。
  • @BrianClozel 当我回答这个问题时,我猜这个关于 WebFlux 的更新不存在。
  • BrianClozel,如何禁用 @EnableWebSecurity。它似乎默认存在,并在我定义反应式弹簧安全性时阻止我的应用程序启动
  • IMO 这真的没有比从类路径中删除 spring 安全依赖项更好。最好是“http.httpBasic().disable().formLogin().disable();”实际工作。文档说“Spring Boot 现在有一个单一的行为,一旦你添加了自己的 WebSecurityConfigurerAdapter,它就会退出。”但这似乎是一个错误的陈述。我有一个 WebSecurityConfigurerAdapter 以及“http.httpBasic().disable().formLogin().disable();”我仍然得到那个愚蠢的春季登录页面。真气。
  • @peekay “Spring Boot 现在有一个单一的行为,一旦你添加了自己的 WebSecurityConfigurerAdapter,它就会退出。” - 这句话是完全正确的。 Spring boot 的任何自动配置功能都是非侵入性的,即一旦您添加了自己的配置,它就会退出。禁用 formLogin() 不会让您在没有用户 ID、密码的情况下访问端点,而是禁用/删除基于表单的身份验证功能。docs.spring.io/spring-security/site/docs/4.2.11.RELEASE/apidocs/…
【解决方案2】:

从 Spring Boot 2.1 开始,如果包含 spring-boot-actuator,仅排除 SecurityAutoconfiguration 是不够的,还需要排除 ManagementWebSecurityAutoConfiguration,如下所示:

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class })

【讨论】:

  • 谢谢!这个答案中的建议有效,当然取决于 Spring Boot 版本(在我的例子中是 2.1.5)。
  • 只要我使用@EnableWebSecurity 注释,这个答案对我不起作用(Spring Boot 2.1.5,spring-security-web 4.2.3.RELEASE)。你还需要做什么吗?
  • 如果你想排除 AutoConfiguration 我相信你将无法使用 @EnableWebSecurity 并且你需要像使用普通 Spring/没有 Spring 启动一样自己配置所需的 Spring Security bean。
  • 最简单的方法。谢谢
【解决方案3】:

According to the reference documentation,允许使用 WebFlux 的所有请求的安全配置应如下所示:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.authorizeExchange().anyExchange().permitAll();
        return http.build();
    }
}

【讨论】:

  • 谢谢!在扩展 WebSecurityConfigurerAdapter 的配置中配置的所有内容似乎都没有做任何事情。但是当删除@EnableWebSecurity 并使用此配置时,它终于可以工作了。
  • @EnableWebSecurity 仅适用于 Spring MVC。 @EnableWebFluxSecurity 如果您在类路径上有 spring 安全性,则会自动应用。请参阅github.com/spring-projects/spring-boot/wiki/… 了解更多信息
  • 我必须明确提到@EnableWebFluxSecuritySecurityConfig
  • 这不起作用,因为它现在抱怨缺少 Bean "ServerHttpSecurity"
  • 我用spring boot 2.2.0试了一下,找不到ServerHttpSecurity'
【解决方案4】:

这对我有用:

@Configuration
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().permitAll();
    }
}

【讨论】:

【解决方案5】:

您可以在您的应用程序类中添加/修改以下内容:

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class MyApplication {

}

【讨论】:

    【解决方案6】:

    添加一些新的答案,我假设所有使用执行器,如果不是,我敢打赌一个类排除就足够了,我设法通过属性禁用:

    spring:
      autoconfigure:
        exclude: ${spring.autoconfigure.sac}, ${spring.autoconfigure.mwsas}
        sac: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
        mwsas: org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration
    

    我通过属性引用了两个自动配置类以保持长度不变(请注意,如果您这样引用它,IntelliJ Ultimate 会哭,因为它不知道这些占位符值是什么以及它们是否实际上是合法类,如果这让你感到厌烦,那么内联)。

    但应用程序并没有按照以下要求启动:

    https://www.baeldung.com/spring-boot-security-autoconfiguration

    如果你只是禁用SecurityAutoConfiguration

    如果它确实有效,您将不再看到自动生成的密码,并且它比接受的答案更容易混淆,因为阅读日志的开发人员不会被生成的基本身份验证密码混淆,而安全性允许一切。

    为什么仅仅禁用主自动配置类是不够的,因为这个家伙:

    @Configuration
    class ManagementWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .requestMatchers(
                            EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class))
                    .permitAll().anyRequest().authenticated().and().formLogin().and()
                    .httpBasic();
        }
    
    }
    

    为了拆分执行器和安全配置,我们做了大量工作,这让我们所有人都感到困惑,现在它更简单了,但像这样的工件仍然存在。如果我错了,Spring 开发人员会纠正我:-)。

    【讨论】:

    • 哦,伙计,这是吨无效建议之间的唯一答案。这个答案绝对应该在线程的顶部。非常感谢!
    • 对于 WebFlux,排除:org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfigurationorg.springframework.boot.actuate.autoconfigure.security.reactive.ReactiveManagementWebSecurityAutoConfiguration
    【解决方案7】:

    如果有人在基于 WebFlux 的应用程序或 Spring Cloud Gateway 应用程序中遇到此问题,以下对我有用:

    @EnableWebFluxSecurity
    public class InsecurityConfiguration {
        // @formatter:off
        @Bean
        public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
             http
                  .authorizeExchange()
                       .anyExchange().permitAll();
             return http.build();
        }
    }
    

    【讨论】:

    • 当我尝试禁用 Spring Cloud Gateway 应用程序的所有安全性时,此解决方案对我有用。
    【解决方案8】:

    我认为您正在寻找的是覆盖设置为 BasicAuthenticationEntryPoint 的默认身份验证入口点。

    这个入口点添加了

    “WWW-Authenticate”:“基本领域=...”

    告诉您的浏览器使用基本身份验证的标头。

    【讨论】:

    • 通过使用 firefox 我没有得到标题,但通过请求工具我得到了它。
    【解决方案9】:

    如果要扩展 WebSecurityConfigurerAdapter,可以将 true 传递给超级构造函数以禁用默认值。
    如果您这样做,您可能需要提供其他 bean。

        /**
         * Creates an instance which allows specifying if the default configuration should be
         * enabled. Disabling the default configuration should be considered more advanced
         * usage as it requires more understanding of how the framework is implemented.
         *
         * @param disableDefaults true if the default configuration should be disabled, else
         * false
         */
        protected WebSecurityConfigurerAdapter(boolean disableDefaults) {
            this.disableDefaults = disableDefaults;
        }
    

    如果您只想出于测试目的禁用它 - 我没有完全禁用自动配置,而是在“SecurityConfiguration”之外创建了一个“InsecurityConfiguration”,并使用 Spring Profile 或 Property 值激活它。

    从技术上讲,安全性仍处于配置状态,但完全开放。

    @Configuration
    @ConditionalOnProperty(prefix = "security", value = "disabled", havingValue = "true")
    public class InsecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        private final static Logger log = LoggerFactory.getLogger(InsecurityConfiguration.class);
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            log.warn("configuring insecure HttpSecurity");
            http.authorizeRequests().anyRequest().permitAll();
        }
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            log.warn("configuring insecure WebSecurity");
            web.ignoring().antMatchers("/**");
        }
    
    }
    

    注意这是针对 mvc,而不是 webflux。对于 Webflux,您应该像 Bryan 提到的那样创建一个 SecurityWebFilterChain

    这就是我在使用 JWT 时通常在 webflux 中禁用基本身份验证的方式 -

        @Bean
        public SecurityWebFilterChain configure(ServerHttpSecurity http) {
    
            http
            .authorizeExchange().anyExchange().authenticated().and()
                .httpBasic().disable()
                .formLogin().disable()
                .logout().disable()
                .oauth2ResourceServer()
                .jwt()
                .and()
                    .and().exceptionHandling().accessDeniedHandler(problemSupport);
            return http.build();
        }
    

    【讨论】:

    • 不知道为什么这被标记了。如果您将某些内容标记下来,提供反馈会很有帮助。
    • 在 Web 安全适配器中覆盖配置方法足以停止默认登录页面 @Override protected void configure(HttpSecurity http) throws Exception { log.warn("configuring insecure HttpSecurity"); http.authorizeRequests().anyRequest().permitAll(); }
    【解决方案10】:

    如果我在 application.yml 中将 spring.security.enabled 属性设置为 false 以禁用 spring 安全性,我已经利用 @ConditionalOnProperty 加载以下 SecurityConfig.java 类,它就像一个魅力。

    @ConditionalOnProperty(name = "spring.security.enabled", havingValue = "false")
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                .authorizeRequests().antMatchers("/").permitAll();
        }
    }
    

    【讨论】:

      【解决方案11】:

      在 Spring boot 2 中,无法通过 application.properties 文件禁用基本身份验证。但唯一的就是使用注解

      @EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})

      在主类中。 有效

      【讨论】:

      • 我无法让它工作。 (Spring Boot 2.1.5、spring-security-web 4.2.3.RELEASE、spring-boot-starter-actuator)。你还需要做什么吗?
      【解决方案12】:

      问题出在 org.springframework.security.web.server.authorization.ExceptionTranslationWebFilter

      它有private ServerAuthenticationEntryPoint authenticationEntryPoint = new HttpBasicServerAuthenticationEntryPoint();

      所以在 ServerHttpSecurity 初始化期间修复它添加:

      http.exceptionHandling().authenticationEntryPoint(HttpStatusServerEntryPoint(HttpStatus.FORBIDDEN))
      

      看起来 vanilla (servlet) spring 使用 org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer#createDefaultEntryPoint

      private AuthenticationEntryPoint createDefaultEntryPoint(H http) {
              if (this.defaultEntryPointMappings.isEmpty()) {
                  return new Http403ForbiddenEntryPoint();
              }
              if (this.defaultEntryPointMappings.size() == 1) {
                  return this.defaultEntryPointMappings.values().iterator().next();
              }
              DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(
                      this.defaultEntryPointMappings);
              entryPoint.setDefaultEntryPoint(this.defaultEntryPointMappings.values().iterator()
                      .next());
              return entryPoint;
          }
      

      旁注:构建器样式 bean 中的可变字段(如 ExceptionTranslationWebFilter)使 Spring 代码难以调试(也太神奇的配置)

      【讨论】:

        【解决方案13】:

        要禁用 Spring Boot Reactive Web 应用程序的默认安全性,请在类路径中也有执行器时使用以下排除项。

        @SpringBootApplication(exclude = {ReactiveSecurityAutoConfiguration.class, ReactiveManagementWebSecurityAutoConfiguration.class })
        

        【讨论】:

          【解决方案14】:

          您应该添加@EnableWebSecurity 以启用自定义安全配置。 之后只需禁用表单登录

          @Configuration
          @EnableWebSecurity
          public class StackWebSecurityConfigurerAdapter extends 
          WebSecurityConfigurerAdapter {
           @Override
           protected void configure(HttpSecurity http) throws Exception {
              http.formLogin().disable();
           }
          

          }

          【讨论】:

            猜你喜欢
            • 2020-11-28
            • 2014-07-16
            • 2020-06-11
            • 2016-05-03
            • 2016-01-02
            • 2019-12-28
            • 2018-08-21
            相关资源
            最近更新 更多