Spring Boot HandBook

    Introduction :#

    To configure a SecurityFilterChain in a Spring Security-based application, you'll typically use the SecurityFilterChain interface to define how security should be applied to HTTP requests.


     

    Here's how you can set up and customize a SecurityFilterChain in your Spring Boot application:

    • Add Dependencies

      Make sure you have the necessary dependencies in your pom.xml file. For Spring Boot, this usually includes:
    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
    • Create a Security Configuration Class

      You can define a SecurityFilterChain in a configuration class. Here’s an example:
    import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; 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.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity //by adding this annotation we are telling springboot that we want to we want to configure this SpringSecurityFilterChain public class WebSecurityConfig { //create a configuration class @Bean SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { httpSecurity .authorizeHttpRequests(auth-> auth .requestMatchers("/<anyEndPoint>/**").permitAll() // give any of your 'get' request endpoint .anyRequest().authenticated()) // All other requests require authentication .csrf(csrfConfig-> // Disable CSRF for simplicity, not recommended for production csrfConfig .disable()) .sessionManagement(sessionConfig -> // Disable JSESSIONID for simplicity, not recommended for production sessionConfig .sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .formLogin(Customizer.withDefaults()) // Enable form login here I use default login .logout(Customizer.withDefaults()); // Enable logout return httpSecurity.build(); //when you add build this throws an exception } // Custom Authentication Providers @Bean UserDetailsService myInMemoryUserDetailsService(){ UserDetails user = User //for user role .withUsername("<UserName>") // Replace <UserName> with the actual username .password(passwordEncoder().encode("<UserPassword>")) // Replace <UserPassword> with the actual password .roles("USER") .build(); UserDetails admin = User //for admin role .withUsername("<AdminName>") // Replace <AdminName> with the actual username .password(passwordEncoder().encode("<AdminPassword>")) // Replace <AdminPassword> with the actual password .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user,admin); } // Password Encoding @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }

     

    • Explanation of Key Components

      • HttpSecurity Configuration: The HttpSecurity object is used to customize security settings. In the example, CSRF is disabled (not recommended for production) and HTTP requests are configured so that any request matching /<any endpoint>/** is permitted without authentication, while all other requests require authentication.
      • Form Login: Form-based login is enabled with a custom login page (/login).
      • Logout: A custom logout URL (/logout) is provided.
      • UserDetailsService: This example uses an in-memory user store for simplicity, but in a real application, you would likely connect to a database or another user management system.
         
    • Running the Application

      When you run the application, any request to paths like /<any end point>/xyz will be accessible without logging in, while other paths will require authentication. The login form will be available at /login.
       
    • Customization

      • Custom Authentication Providers: If you need custom authentication logic, you can create and configure an AuthenticationProvider bean. If you were developing a simple REST API where you wanted to protect certain endpoints and only allow access to users with specific roles, but you didn't want to set up a database just for this, you might use in-memory authentication as shown above.
      • Password Encoding: Use a proper PasswordEncoder for production environments.
      • CSRF Protection: For most applications, you should enable and properly configure CSRF protection.

    Default SecurityFilterChain Config:#

    • authorizeRequests() restricts access based on RequestMatcher implementations.
       
    • authenticated() requires that all endpoints called be authenticated before proceeding in the filter chain.
       
    • formLogin() calls the default FormLoginConfigurer class that loads the login page to authenticate via username-password and accordingly redirects to corresponding failure or success handlers.
       
    • csrf() to cofigure the csrf protection.
       
    • sessionManagement() to configure session management for your application.

    Last updated on Dec 09, 2024