Spring Boot 2.0 disable default security

后端 未结 11 2610
闹比i
闹比i 2020-12-02 11:28

I want to use Spring Security for JWT authentication. But it comes with default authentication. I am trying to disable it, but the old approach of doing this - disabling it

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 11:53

    If you're extending WebSecurityConfigurerAdapter, you can pass in true to the super constructor to disable the defaults.
    You may need to provide other beans if you do this.

        /**
         * 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;
        }
    

    If you want to disable it just for testing purposes - Rather than completely disabling the auto-configuration, I create an "InsecurityConfiguration" in addition to "SecurityConfiguration", and activate it with either a Spring Profile or Property value.

    Technically security is still configured, but wide open.

    @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("/**");
        }
    
    }
    

    Note This is for mvc, not webflux. For Webflux you should create a SecurityWebFilterChain like Bryan mentioned.

    This is how I generally disable basic auth in webflux, when using JWT -

        @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();
        }
    

提交回复
热议问题