What is Spring Boot Security?
Spring Boot Security is a powerful security framework built on top of Spring Security that provides authentication, authorization, protection against attacks, and secure access control for Spring Boot applications.
It helps developers secure web applications, REST APIs, microservices, and enterprise systems with minimal configuration.
In simple words, Spring Boot Security protects applications from unauthorized access and common security vulnerabilities.
Why Security is Important in Applications
Modern applications handle sensitive data such as:
- User credentials
- Banking transactions
- Personal information
- Payment details
- Company data
- Medical records
Without security:
- Hackers may access sensitive data
- Unauthorized users may access APIs
- Applications become vulnerable to attacks
- User accounts may be compromised
- Business data may leak
Spring Boot Security helps prevent these risks.
Main Features of Spring Boot Security
- Authentication
- Authorization
- Password encryption
- Role-based access control
- JWT authentication
- OAuth2 support
- Session management
- CSRF protection
- CORS configuration
- Protection against common attacks
What is Authentication?
Authentication means verifying the identity of a user.
Example:
- Username and password login
- OTP verification
- JWT token validation
- Google login
Authentication answers:
โWho are you?โ
What is Authorization?
Authorization means checking whether the authenticated user has permission to access specific resources.
Example:
- Admin can delete users
- Student can view courses
- Manager can approve leave requests
Authorization answers:
โWhat are you allowed to do?โ
Authentication vs Authorization
| Feature | Authentication | Authorization |
|---|---|---|
| Purpose | Verify identity | Check permissions |
| Main Question | Who are you? | What can you access? |
| Example | Login | Role-based access |
Spring Boot Security Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
What Happens After Adding Spring Security?
Once the security dependency is added:
- All endpoints become secured automatically
- Spring Boot creates default login page
- Default username becomes
user - Random password is generated in console
Default Spring Security Login
Console Output Example:
Using generated security password:
a8f7d2c1-1234-5678-9876
Simple Security Configuration Example
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(
HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**")
.permitAll()
.anyRequest()
.authenticated()
)
.formLogin(Customizer.withDefaults());
return http.build();
}
}
How Spring Security Works Internally
Spring Security works using filters.
Request Flow:
- Client sends HTTP request
- Security filters intercept request
- Authentication is checked
- Authorization rules are validated
- Access is granted or denied
What is SecurityFilterChain?
SecurityFilterChain defines security rules
for incoming HTTP requests.
It replaces older WebSecurityConfigurerAdapter
in modern Spring Security versions.
Role-Based Authentication Example
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**")
.hasRole("ADMIN")
.requestMatchers("/student/**")
.hasRole("STUDENT")
.anyRequest()
.authenticated()
)
Password Encryption in Spring Security
Passwords should never be stored as plain text.
Spring Security uses:
- BCrypt
- PasswordEncoder
BCrypt Password Example
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
Encoding Password
String encodedPassword =
passwordEncoder.encode("admin123");
Why BCrypt is Important
- Passwords become encrypted
- Hackers cannot easily read passwords
- Improves application security
What is JWT Authentication?
JWT (JSON Web Token) authentication is widely used in modern REST APIs.
Process:
- User logs in
- Server generates JWT token
- Client stores token
- Client sends token in every request
- Server validates token
JWT Header Example
Authorization: Bearer eyJhbGciOiJIUzI1Ni...
Advantages of JWT
- Stateless authentication
- Scalable for microservices
- No session storage needed
- Works well with frontend frameworks
What is OAuth2?
OAuth2 allows users to log in using external providers such as:
- GitHub
Example
โLogin with Googleโ
CSRF Protection in Spring Security
CSRF stands for:
Cross-Site Request Forgery
Spring Security automatically enables CSRF protection for web applications.
Disable CSRF for REST APIs
http.csrf(csrf -> csrf.disable());
What is CORS?
CORS stands for:
Cross-Origin Resource Sharing
It controls which frontend applications can access backend APIs.
CORS Configuration Example
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(
CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(
"http://localhost:3000"
);
}
};
}
Real-Time Example in Banking Application
Suppose a banking application has:
- Customer login
- Admin dashboard
- Money transfer APIs
- Transaction history APIs
Spring Security helps:
- Authenticate users securely
- Restrict admin APIs
- Protect transactions
- Encrypt passwords
- Validate JWT tokens
Common Spring Security Annotations
| Annotation | Purpose |
|---|---|
| @EnableWebSecurity | Enables Spring Security |
| @PreAuthorize | Method-level authorization |
| @Secured | Role-based method access |
| @RolesAllowed | Role restriction |
Method-Level Security Example
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin")
public String adminDashboard() {
return "Admin Dashboard";
}
Advantages of Spring Boot Security
- Powerful authentication system
- Role-based authorization
- Password encryption support
- JWT and OAuth2 support
- Protection against common attacks
- Enterprise-grade security
- Highly customizable
Disadvantages of Spring Security
- Learning curve can be high
- Complex configuration for beginners
- JWT implementation may become complicated
- Improper configuration may create vulnerabilities
Best Practices for Spring Boot Security
- Always encrypt passwords using BCrypt
- Use JWT for stateless APIs
- Restrict sensitive endpoints
- Never expose sensitive exception details
- Use HTTPS in production
- Enable proper CORS configuration
- Implement role-based access control
- Use refresh tokens securely
Common Security Vulnerabilities Prevented
| Attack Type | Protection |
|---|---|
| CSRF | CSRF Tokens |
| Session Hijacking | Secure session management |
| Password Theft | BCrypt encryption |
| Unauthorized Access | Authentication & Authorization |
Difference Between Authentication and JWT
| Feature | Session Authentication | JWT Authentication |
|---|---|---|
| State | Stateful | Stateless |
| Storage | Server Session | Client Token |
| Scalability | Moderate | High |
| Microservices Support | Limited | Excellent |
Common Interview Questions on Spring Boot Security
What is Spring Boot Security?
Spring Boot Security is a framework used for authentication, authorization, and securing Spring Boot applications.
What is the difference between authentication and authorization?
Authentication verifies identity, while authorization checks permissions.
Why is BCrypt used?
BCrypt encrypts passwords securely and protects against password theft.
What is JWT?
JWT is a stateless token-based authentication mechanism widely used in REST APIs and microservices.
Why is Spring Security important?
It protects applications from unauthorized access, attacks, and security vulnerabilities.
Conclusion
Spring Boot Security is one of the most important modules in enterprise application development.
It provides authentication, authorization, password encryption, JWT support, OAuth2 integration, and protection against common attacks.
Proper security implementation is critical for protecting sensitive user data and building secure REST APIs, microservices, banking systems, and enterprise applications.
Understanding Spring Boot Security is essential for backend developers because security is a mandatory requirement in modern software systems.