49

我想使用 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。

截屏:
基本登录表单

4

14 回答 14

64

根据 Spring 2.0 中的新更新,如果 Spring Security 在类路径中,Spring Boot 将添加 @EnableWebSecurity。因此,向 application.properties 添加条目将不起作用(即,它不再是可定制的方式)。更多信息请访问官网Spring Boot 2.0 中的安全变化

尽管不确定您的确切要求,但我可以想到一种解决方法,如下所示:-

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

希望这可以帮助。

于 2018-04-04T08:37:17.607 回答
39

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

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class })
于 2019-05-10T12:44:19.413 回答
19

根据参考文档,允许使用 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();
    }
}
于 2017-11-14T17:44:29.740 回答
18

这对我有用:

@Configuration
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().permitAll();
    }
}
于 2018-03-16T18:05:32.830 回答
15

您可以在 Application 类中添加/修改以下内容:

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

}
于 2018-08-28T16:26:04.100 回答
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 开发人员会纠正我:-)。

于 2019-03-06T18:13:34.067 回答
2

如果有人在基于 WebFlux 的应用程序或 Spring Cloud Gateway 应用程序中为此苦苦挣扎,以下内容对我有用:

@EnableWebFluxSecurity
public class InsecurityConfiguration {
    // @formatter:off
    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
         http
              .authorizeExchange()
                   .anyExchange().permitAll();
         return http.build();
    }
}
于 2020-05-08T18:00:18.237 回答
1

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

这个入口点添加了

"WWW-Authenticate": "基本领域=..."

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

于 2017-11-14T15:13:44.633 回答
1

如果要扩展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;
    }

如果您只想出于测试目的禁用它 - 除了完全禁用自动配置之外,我还创建了一个“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,您应该创建一个SecurityWebFilterChain类似 Bryan 提到的。

这就是我在使用 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();
    }
于 2019-12-15T20:26:19.697 回答
1

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

@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();
    }
}
于 2021-01-28T14:38:31.073 回答
0

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

@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})

在主班。有用

于 2019-02-20T03:43:49.340 回答
0

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

它有private ServerAuthenticationEntryPoint authenticationEntryPoint = new HttpBasicServerAuthenticationEntryPoint();

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

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

看起来香草(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 代码难以调试(也太神奇的配置)

于 2019-07-13T23:25:32.740 回答
0

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

@SpringBootApplication(exclude = {ReactiveSecurityAutoConfiguration.class, ReactiveManagementWebSecurityAutoConfiguration.class })
于 2021-02-20T10:30:54.820 回答
0

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

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

}

于 2021-08-11T18:58:40.183 回答