[英]How to optionally use basic authentication in Spring Security
I want to use basic authentication when properties exist in application.yml
.当
application.yml
中存在属性时,我想使用基本身份验证。 When they're missing I want all requests to be allowed.当他们失踪时,我希望允许所有请求。
application.yml
spring:
security:
user:
name: user
password: changeit
Auth configuration认证配置
@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();
}
}
This works perfectly.这完美地工作。
But what about making it optional?但是让它成为可选的呢? If
spring.security.user.name/password
properties are missing I want zero authentication.如果缺少
spring.security.user.name/password
属性,我想要零身份验证。 How can I do this?我怎样才能做到这一点?
What about using Spring Boot's @ConditionalOnProperty
?使用 Spring 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();
}
}
Instead of using a Spring Boot property, you could create your own property to be more explicitly about the behavior, like so:您可以创建自己的属性来更明确地说明行为,而不是使用 Spring Boot 属性,如下所示:
myapp:
security:
permit-all: true
And then you can change yours @ConditionalOnProperty
to match on this property, this way it is more declarative about what it's doing.然后你可以改变你
@ConditionalOnProperty
来匹配这个属性,这样它就更能说明它在做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.