代码之家  ›  专栏  ›  技术社区  ›  Jan Wytze

Spring Boot 2.0禁用默认安全性

  •  50
  • Jan Wytze  · 技术社区  · 7 年前

    我想使用Spring安全性进行JWT身份验证。但它附带了默认身份验证。我正试图禁用它,但旧的做法是通过 application.properties

    这就是我尝试的:

    @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。

    截图:
    Basic login form

    15 回复  |  直到 6 年前
        1
  •  66
  •   Sen    7 年前

    根据Spring 2.0中的新更新,如果Spring安全性在类路径上,Spring引导将添加@EnableWebSecurity。因此,在应用程序中添加条目。属性将不起作用(即不再以这种方式进行自定义)。有关更多信息,请访问官方网站 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();
        }
    }
    

    希望这有帮助。

        2
  •  41
  •   Integrating Stuff    6 年前

    从Spring Boot 2.1开始,如果您包括Spring Boot actuator,那么只排除SecurityAutoconfiguration已经不够了,您还需要排除ManagementWebSecurityAutoConfiguration,如下所示:

    @SpringBootApplication(exclude = { SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class })
    
        3
  •  20
  •   Brian Clozel    7 年前

    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();
        }
    }
    
        4
  •  19
  •   davo    7 年前

    这对我很有效:

    @Configuration
    public class SecurityConfig  extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable().authorizeRequests().anyRequest().permitAll();
        }
    }
    
        5
  •  16
  •   helmy    6 年前

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

    @SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
    public class MyApplication {
    
    }
    
        6
  •  6
  •   Aubergine    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,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开发人员会纠正我:-)。

        7
  •  2
  •   odedia    5 年前

    如果有人在基于WebFlux的应用程序或Spring Cloud Gateway应用程序中对此感到困扰,那么以下内容对我来说很有用:

    @EnableWebFluxSecurity
    public class InsecurityConfiguration {
        // @formatter:off
        @Bean
        public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
             http
                  .authorizeExchange()
                       .anyExchange().permitAll();
             return http.build();
        }
    }
    
        8
  •  1
  •   Marvin    7 年前

    我认为您想要的是覆盖默认的身份验证入口点,该入口点设置为 基本认证入口点 .

    此入口点添加了

    “WWW认证”:“基本领域=…”

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

        9
  •  1
  •   Jeremy    5 年前

    如果你要延长 WebSecurityConfigurerAdapter ,你可以进来 true 以禁用默认值。

        /**
         * 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”之外创建了一个“unsecurityconfiguration”,并使用Spring配置文件或属性值来激活它。

    从技术上讲,安全性仍在配置中,但完全开放。

    @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,您应该创建一个 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();
        }
    
        10
  •  1
  •   Ashraf Sarhan    4 年前

    我利用了 @ConditionalOnProperty 加载以下内容 SecurityConfig.java 类,如果我设置 spring.security.enabled 属性设置为false。yml禁用spring security,它就像一个符咒。

    @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
  •  1
  •   Varesh    4 年前

    @SpringBootApplication(exclude = {ReactiveSecurityAutoConfiguration.class, ReactiveManagementWebSecurityAutoConfiguration.class })
    
        12
  •  0
  •   Book Of Zeus jakob    6 年前

    在Spring boot 2中,无法通过应用程序禁用基本身份验证。属性文件。但唯一的问题是使用注释

    @EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})

    在主课上。 它起作用了

        13
  •  0
  •   ichaki5748    5 年前

    问题在于组织。springframework。安全网状物服务器批准例外TranslationWebFilter

    它有 private ServerAuthenticationEntryPoint authenticationEntryPoint = new HttpBasicServerAuthenticationEntryPoint();

    因此,要在ServerHttpSecurity初始化期间修复它,请添加:

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

    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代码难以调试(配置也太神奇了)

        14
  •  0
  •   Irshad    3 年前

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

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

    }

        15
  •  0
  •   Andrey D.    2 年前

    仅限房地产-适用于我(sb2-2022):

    spring:
      autoconfigure:
        exclude:
          - org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
          - org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration