Skip to content

Instantly share code, notes, and snippets.

@mike-seger
Last active November 3, 2024 11:43
Show Gist options
  • Save mike-seger/ee80a8a8af04ab2651337472d6ead5e6 to your computer and use it in GitHub Desktop.
Save mike-seger/ee80a8a8af04ab2651337472d6ead5e6 to your computer and use it in GitHub Desktop.

You:

i have a spring security enabled test application currently configured with a single test user in application.yaml: spring: security.user: name: user password: pw

the goal is to modify this setup to allow 2 distinct users (user1, user2) basic auth access through a SecurityFilterChain, permitting user1 access to a resource antMatchers("/dir1/") and user2 access to a resource antMatchers("/dir2/") The users should have an empty password.

ChatGPT:

To configure multiple users with different access permissions in a Spring Security setup, you can use SecurityFilterChain and configure each user with specific antMatchers. Here’s how you can set up your configuration to achieve this:

  1. Remove the single-user configuration in application.yaml.

  2. Create a custom security configuration class where you define two distinct users and set their access permissions for different URL patterns.

Here’s a sample implementation:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/dir2/**").hasAnyRole("USER1", "USER2") 
                .antMatchers("/dir1/**").hasRole("USER1")
                .antMatchers("/dir2/**").hasRole("USER2")
                .anyRequest().authenticated()
            .and()
            .httpBasic();
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        UserDetails user1 = User.builder()
            .username("user1")
            .password(passwordEncoder.encode(""))  // Empty password
            .roles("USER1")
            .build();

        UserDetails user2 = User.builder()
            .username("user2")
            .password(passwordEncoder.encode(""))  // Empty password
            .roles("USER2")
            .build();

        return new InMemoryUserDetailsManager(user1, user2);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return rawPassword.toString(); // No encoding for demonstration purposes
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return rawPassword.toString().equals(encodedPassword);
            }
        };
    }
}

Explanation:

  • SecurityFilterChain : Configures access rules for different URL patterns. Only user1 can access URLs under /dir1/**, and only user2 can access URLs under /dir2/**.

  • UserDetailsService : Creates two in-memory users, each with a distinct role (USER1 and USER2). Basic authentication is enabled. Now user1 can access resources under /dir1/** and user2 under /dir2/**.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment