Category: spring_boot
Spring Security
Published on 26 Jun 2026
Explanation
Spring Security is a powerful framework
used to secure Spring Boot applications.
It provides authentication,
authorization, password encryption,
session management,
and protection against common
security vulnerabilities.
Code:
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-security
</artifactId>
</dependency>
Explanation
By default, Spring Security secures all
endpoints and generates a
temporary password.
A SecurityFilterChain bean can be used
to customize access rules for REST
APIs.
@Configuration
public class SecurityConfig {
}
Code:
@Bean
public SecurityFilterChain
securityFilterChain(HttpSecurity http)
throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(
auth -> auth
.anyRequest().authenticated()
)
.httpBasic();
return http.build();
}
}
Explanation
Authentication verifies the identity of a
user. In-memory authentication is
commonly used
for learning and testing purposes, where
users and roles are configured directly
in code.
Code:
@Bean
public UserDetailsService
userDetailsService() {
UserDetails user = User.builder()
.username("admin")
.password(passwordEncoder()
.encode("admin123"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(
user);
}
Explanation
PasswordEncoder is used to securely hash
passwords before storing them.
BCryptPasswordEncoder is
the most commonly used implementation in
Spring Security.
Code:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
Explanation
Authorization controls which users
can access
specific endpoints.
Roles such as ADMIN
and USER can be assigned, and
access can be restricted using request
matchers.
@Bean
public SecurityFilterChain
securityFilterChain(HttpSecurity http)
throws Exception {
}
Code:
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(
auth -> auth
.requestMatchers("/admin/**")
.hasRole("ADMIN")
.requestMatchers("/users/**")
.hasAnyRole("USER", "ADMIN")
.anyRequest()
.authenticated()
)
.httpBasic();
return http.build();
}