Spring Boot Security – Authentication &
Authorization
1. What is Spring Security?
Spring Security is a powerful and highly customizable authentication and access-control
framework. It is the standard for securing Spring-based applications, providing protection
against common attacks like CSRF, session fixation, and clickjacking.
Concept Description
Authentication Who are you? (login)
Authorization What can you do? (permissions)
Principal Currently logged-in user
GrantedAuthority Role or permission assigned to user
SecurityContext Holds authentication of current thread
2. Maven Dependency
[Link]
spring-boot-starter-security
[Link]
jjwt-api
0.11.5
3. Security Configuration (Spring Boot 3.x)
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception
{
http
.csrf(csrf -> [Link]())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.sessionManagement(session -> session
.sessionCreationPolicy([Link])
);
return [Link]();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
4. JWT Authentication Flow
Step Action
1 User sends POST /login with credentials
2 Server validates credentials
3 Server generates JWT token and returns it
4 Client stores token (localStorage/cookie)
5 Client sends token in Authorization header
6 Server validates token on every request
7 Server grants or denies access
5. Common Security Annotations
Annotation Description
@EnableWebSecurity Enables Spring Security
@PreAuthorize Method-level security before execution
@PostAuthorize Method-level security after execution
@Secured Restricts method to specific roles
@RolesAllowed JSR-250 role-based access
@RestController
public class AdminController {
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/api/admin/users")
public List getAllUsers() {
return [Link]();
}
@PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
@GetMapping("/api/reports")
public List getReports() {
return [Link]();
}
}