[Pratik Merekar]


PROJECT: Simple Spring Security Authentication Demonstration

12 Dec, 2024


Repository link: https://github.com/ProgrammerPratik/java-spring-security


Overview:

This is a simple Spring Boot MVC application project demonstrating basic web security implementation using Spring Security, Thymeleaf, and authentication mechanisms. Looks kinda simple, but demonstrates security principles like Route protection, Authentication, Login/Logout mechanisms, User role management very well.




features:


Simple illustration explaining flow of working:

flowchart

Technologies Used:


Running the Application:

  1. Clone the repository:
    git clone https://github.com/ProgrammerPratik/java-spring-security
    cd java-spring-security
  2. Ensure Java version 23 and Maven are installed (this specific project uses java 23)
  3. Run mvnw spring-boot:run OR you can use any IDE like intellij to build and run project
  4. Access at http://localhost:8080

Default Demo Login Credentials (can be changed)


Key Configuration Components:

WebSecurityConfig.java

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((requests) -> 
                requests
                    .requestMatchers("/", "/home").permitAll()
                    .anyRequest().authenticated()
            )
            .formLogin((form) -> 
                form
                    .loginPage("/login")
                    .permitAll()
            )
            .logout((logout) -> 
                logout.permitAll()
            );
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

Security Flow:

  1. Public routes ("/", "/home") are accessible WITHOUT login
  2. All other routes require authentication
  3. Custom login page at "/login"
  4. In-memory user authentication (user/password)