PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 4, 2022

[FIXED] How to optionally use basic authentication in Spring Security

 September 04, 2022     authentication, java, spring-boot, spring-security     No comments   

Issue

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?


Solution

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.



Answered By - Marcus Hert da Coregio
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing