Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring Security Project Example using Java Configuration

Creating a Spring Security project using Java configuration involves several steps. Below is a basic example of setting up Spring Security with form-based authentication using Java-based configuration:

  1. Add Dependencies:

    First, make sure you have the necessary Spring Security and Spring Boot dependencies in your pom.xml:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    
  2. Security Configuration:

    Define a configuration class that extends WebSecurityConfigurerAdapter:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/public/**").permitAll()
                    .anyRequest().authenticated()
                .and()
                .formLogin()
                    .loginPage("/login")
                    .defaultSuccessURL("/home")
                    .permitAll()
                .and()
                .logout()
                    .logoutSuccessURL("/login?logout")
                    .permitAll();
        }
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth
                .inMemoryAuthentication()
                .withUser("user").password(passwordEncoder().encode("password")).roles("USER");
        }
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    }
    
  3. Controller:

    Create a controller to handle different endpoints:

    @Controller
    public class AppController {
    
        @GetMapping("/public/hello")
        @ResponseBody
        public String publicHello() {
            return "Hello, Public!";
        }
    
        @GetMapping("/secure/hello")
        @ResponseBody
        public String secureHello() {
            return "Hello, Secure!";
        }
    
        @GetMapping("/login")
        public String login() {
            return "login";  // Assumes you have a 'login.html' in your template folder.
        }
    
        @GetMapping("/home")
        public String home() {
            return "home";  // Assumes you have a 'home.html' in your template folder.
        }
    }
    
  4. Templates:

    Create a login.html template (and any other templates you may need):

    <!DOCTYPE html>
    <html>
    <head>
        <title>Login</title>
    </head>
    <body>
        <form action="/login" method="post">
            <div>
                <label>Username:</label>
                <input type="text" name="username"/>
            </div>
            <div>
                <label>Password:</label>
                <input type="password" name="password"/>
            </div>
            <div>
                <input type="submit" value="Login"/>
            </div>
        </form>
    </body>
    </html>
    
  5. Application Class:

    Create the main application class:

    @SpringBootApplication
    public class SpringSecurityExampleApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringSecurityExampleApplication.class, args);
        }
    }
    
  6. Running:

    Run the SpringSecurityExampleApplication class. When you try to access any endpoint (other than /public/**), you'll be redirected to the /login page. Once you provide the credentials (user/password), you will be directed to /home.

This example provides a basic setup for Spring Security using Java configuration. Depending on your requirements, you can expand on this by connecting to a database for user data, using custom authentication providers, adding method-level security, and much more.

  1. Securing Spring application with Java-based Spring Security:

    • Description: This example demonstrates the basic setup of Spring Security to secure a Spring application.
    • Code:
      @EnableWebSecurity
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
          // Configure authentication and authorization here
      }
      
  2. Building a secure web application with Spring Security Java config:

    • Description: Illustrates how to secure a web application using Spring Security's Java configuration.
    • Code:
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
              .authorizeRequests()
                  .antMatchers("/public/**").permitAll()
                  .anyRequest().authenticated()
                  .and()
              .formLogin().and()
              .logout().logoutSuccessUrl("/login");
      }
      
  3. Configuring authentication and authorization in Spring Security using Java:

    • Description: Focuses on configuring user authentication and authorization using Spring Security Java configuration.
    • Code:
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth
              .inMemoryAuthentication()
                  .withUser("user").password("{noop}password").roles("USER");
      }
      
  4. Securing RESTful APIs with Spring Security Java config:

    • Description: Demonstrates how to secure RESTful APIs using Spring Security's Java configuration.
    • Code:
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
              .authorizeRequests()
                  .antMatchers("/api/**").authenticated()
                  .and()
              .httpBasic();
      }
      
  5. Spring Security Java configuration custom login form:

    • Description: Shows how to customize the login form in a Spring Security Java configuration.
    • Code:
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
              .formLogin()
                  .loginPage("/custom-login")
                  .permitAll();
      }
      
  6. Java-based Spring Security for Spring Boot projects:

    • Description: Guides on setting up Spring Security for a Spring Boot project using Java configuration.
    • Code:
      @SpringBootApplication
      public class MyApplication {
          public static void main(String[] args) {
              SpringApplication.run(MyApplication.class, args);
          }
      }
      
  7. Role-based access control in Spring Security Java configuration:

    • Description: Demonstrates how to implement role-based access control using Spring Security Java configuration.
    • Code:
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
              .authorizeRequests()
                  .antMatchers("/admin/**").hasRole("ADMIN")
                  .antMatchers("/user/**").hasRole("USER")
                  .and()
              .formLogin();
      }
      
  8. Customizing password encoding with Spring Security Java config:

    • Description: Shows how to customize password encoding in Spring Security using Java configuration.
    • Code:
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth
              .inMemoryAuthentication()
                  .passwordEncoder(new BCryptPasswordEncoder())
                  .withUser("user").password("$2a$10$...").roles("USER");
      }
      
  9. Configuring session management with Spring Security Java config:

  • Description: Explains how to configure session management in Spring Security using Java configuration.
  • Code:
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
    }
    
  1. Spring Security Java configuration for method-level security:
  • Description: Shows how to enable method-level security with Spring Security Java configuration.
  • Code:
    @EnableGlobalMethodSecurity(securedEnabled = true)
    public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
        // Configure method-level security settings
    }
    
  1. Implementing Remember Me functionality with Spring Security Java config:
  • Description: Guides on implementing "Remember Me" functionality using Spring Security Java configuration.
  • Code:
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .rememberMe()
                .key("uniqueAndSecret");
    }
    
  1. Spring Security Java config with LDAP authentication:
  • Description: Demonstrates how to configure Spring Security for LDAP authentication using Java configuration.
  • Code:
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .ldapAuthentication()
                .userDnPatterns("uid={0},ou=people")
                .groupSearchBase("ou=groups");
    }
    
  1. Securing multiple URL patterns with Spring Security Java config:
  • Description: Illustrates how to secure multiple URL patterns using Spring Security Java configuration.
  • Code:
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .and()
            .formLogin();
    }
    
  1. Java configuration for CSRF protection in Spring Security: