Home > OS >  How to optionally use basic authentication in Spring Security
How to optionally use basic authentication in Spring Security

Time:07-08

I want to use basic authentication when properties exist in 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. How can I do this?

CodePudding user response:

What about using Spring Boot's @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:

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.

  • Related