spring-security 如何在Spring Security中选择性地使用基本身份验证

3zwjbxry  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(130)

application.yml中存在属性时,我想使用基本身份验证。当它们丢失时,我想允许所有请求。
application.yml

spring:
 security:
   user:
     name: user
     password: changeit

身份验证配置

@Configuration
@EnableWebSecurity
public class BasicAuthConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeRequests(authorize -> authorize
            .anyRequest().authenticated()
        )
        .httpBasic(Customizer.withDefaults());
    http.cors().disable().csrf().disable();

    return http.build();
}
}

这个很好用。
如果spring.security.user.name/password属性丢失了,我希望不进行身份验证,我该怎么做呢?

zpgglvta

zpgglvta1#

使用Sping Boot 的@ConditionalOnProperty怎么样?

@EnableWebSecurity
public class BasicAuthConfig {
    @Bean
    @ConditionalOnProperty(prefix = "spring", name = "security.user.name")
    public SecurityFilterChain basicFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .httpBasic(Customizer.withDefaults());
        http.cors().disable().csrf().disable();

        return http.build();
    }

    @Bean
    @ConditionalOnProperty(prefix = "spring", name = "security.user.name", matchIfMissing = true)
    public SecurityFilterChain permitAllFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(requests -> requests
            .anyRequest().permitAll()
        );
        return http.build();
    }
}

您可以不使用Sping Boot 属性,而是建立自己的属性,以更明确地说明行为,如下所示:

myapp:
  security:
    permit-all: true

然后你可以改变你的@ConditionalOnProperty来匹配这个属性,这样它就更能说明它在做什么。

相关问题