Category: java
Introduction to Spring Security
Published on 24 Jul 2026
Explanation
Spring Security is a powerful framework that protects Spring Boot applications from unauthorized access. It provides authentication, authorization, password encryption, session management, and protection against common security vulnerabilities with minimal configuration.
Code:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Explanation
Spring Security uses SecurityFilterChain to define security rules for HTTP requests. Developers can specify which endpoints are public, which require authentication, and customize login or access-denied behavior.
Code:
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.formLogin();
return http.build();
}
Explanation
Authentication verifies the identity of a user by checking credentials such as username and password. Authorization determines what resources or operations the authenticated user is allowed to access based on assigned roles or permissions.
Code:
Authentication β Who are you? Authorization β What are you allowed to access?
Explanation
Passwords should never be stored in plain text. Spring Security provides BCryptPasswordEncoder to hash passwords before storing them in the database and to verify passwords securely during user authentication.
Code:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
String encrypted = passwordEncoder().encode("password123");
Explanation
For development and testing, Spring Security supports in-memory authentication. User credentials and roles are stored in memory, eliminating the need for a database while learning or building prototypes.
Code:
@Bean
public UserDetailsService users() {
UserDetails user = User.withUsername("admin")
.password(passwordEncoder().encode("admin123"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user);
}