In this guide, we'll cover the Top 10 Spring Boot Security Mistakes and how to fix them with real-world examples.
1️⃣ Not Enforcing HTTPS 🚫🔓
❌ Mistake: Allowing HTTP Requests
By default, Spring Boot does not enforce HTTPS, leaving applications vulnerable to man-in-the-middle (MITM) attacks.
@GetMapping("/secure-data")
public String getSecureData() {
return "Sensitive Information"; // ❌ Accessible over HTTP
}
✅ Solution: Redirect All HTTP Requests to HTTPS
Configure Spring Security to redirect HTTP requests to HTTPS.
Step 1: Enable HTTPS in application.properties
server.port=8443
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=yourpassword
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias=tomcat
Step 2: Force HTTPS Redirection
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.requiresChannel(channel -> channel
.anyRequest().requiresSecure() // ✅ Force HTTPS
);
return http.build();
}
}
✔ Best Practice: Use Let's Encrypt to get a free SSL certificate.
2️⃣ Hardcoding Secrets in Code 🔑
❌ Mistake: Storing API Keys in Code
private static final String API_KEY = "my-secret-key"; // ❌ Bad practice
✅ Solution: Store Secrets Securely
Use environment variables or Spring Boot’s configuration files.
api.key=${API_KEY}
✔ Best Practice: Use Spring Cloud Config, AWS Secrets Manager, or Vault.
3️⃣ Using Default Database Credentials 🛑
❌ Mistake: Keeping Default Credentials
spring.datasource.username=root
spring.datasource.password=root
✔ Issue: Attackers try default passwords first.
✅ Solution: Use Strong, Secure Credentials
spring.datasource.username=secure_user
spring.datasource.password=strong_password_123!
✔ Best Practice: Store credentials in environment variables or secrets vaults.
4️⃣ Exposing Actuator Endpoints Publicly 📡
❌ Mistake: Leaving Actuator Endpoints Open
Spring Boot Actuator provides helpful endpoints (/health
, /metrics
, etc.), but exposing them publicly is a risk.
management.endpoints.web.exposure.include=*
✔ Issue: Attackers can gain insights into system health, environment variables, and logs.
✅ Solution: Restrict Access
management.endpoints.web.exposure.include=health,info
management.endpoints.web.base-path=/management
management.endpoint.health.show-details=never
✔ Best Practice: Use authentication for sensitive endpoints.
5️⃣ Not Securing REST APIs (Missing Authentication) 🔓
❌ Mistake: Leaving APIs Open to Anyone
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users")
public List<User> getUsers() {
return userService.getAllUsers(); // ❌ Public API
}
}
✔ Issue: No authentication, meaning anyone can access it.
✅ Solution: Secure APIs Using OAuth2 + JWT
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
).oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
return http.build();
}
}
✔ Best Practice: Use JWT (JSON Web Tokens) or OAuth2 for API security.
6️⃣ Allowing CORS from Any Origin 🌍
❌ Mistake: Allowing All Origins
@CrossOrigin("*") // ❌ Allows requests from ANY domain
@RestController
@RequestMapping("/api")
public class UserController { }
✔ Issue: Attackers can exploit CORS misconfigurations to perform cross-origin attacks.
✅ Solution: Restrict Allowed Origins
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://trusted.com") // ✅ Allow specific origins
.allowedMethods("GET", "POST");
}
};
}
}
✔ Best Practice: Allow only trusted domains.
7️⃣ Exposing Sensitive Data in Logs 📝
❌ Mistake: Logging User Data
logger.info("User logged in: " + user.getEmail()); // ❌ Logs sensitive info
✔ Issue: Attackers can access log files and extract personal information.
✅ Solution: Use Masking for Sensitive Logs
logger.info("User logged in: {}", maskEmail(user.getEmail()));
✔ Best Practice: Use log masking tools like logback.
8️⃣ Not Implementing Rate Limiting ⏳
❌ Mistake: No Protection Against Brute Force Attacks
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest request) {
return authService.authenticate(request);
}
✔ Issue: Attackers can flood login attempts, causing DDoS.
✅ Solution: Implement Rate Limiting
Use Spring Boot Resilience4J to prevent abuse.
@Bean
public RateLimiterConfig rateLimiterConfig() {
return RateLimiterConfig.custom()
.limitRefreshPeriod(Duration.ofSeconds(10))
.limitForPeriod(5) // ✅ Allow only 5 requests per 10 seconds
.build();
}
✔ Best Practice: Use API gateways like Cloudflare, AWS API Gateway.
9️⃣ Not Encrypting Sensitive Data in the Database 🔐
❌ Mistake: Storing Passwords in Plain Text
user.setPassword("mypassword"); // ❌ Visible in the database
✔ Issue: If the database is breached, all passwords are exposed.
✅ Solution: Use BCrypt for Password Hashing
user.setPassword(new BCryptPasswordEncoder().encode("mypassword")); // ✅ Secure
✔ Best Practice: Always hash passwords before storing.
🔟 Running the Application in Debug Mode in Production 🛑
❌ Mistake: Keeping Debug Mode Enabled
spring.profiles.active=dev
logging.level.root=DEBUG
✔ Issue: Debug logs expose internal details, making it easier for attackers.
✅ Solution: Disable Debugging in Production
spring.profiles.active=prod
logging.level.root=INFO
✔ Best Practice: Use Spring Profiles to switch between dev/prod environments.
🎯 Conclusion
Security is critical in any Spring Boot application. The mistakes listed above can expose your application to vulnerabilities, but by following best practices, you can keep your application secure.
Quick Recap
✔ Use HTTPS and enforce SSL
✔ Store secrets securely (no hardcoded API keys)
✔ Secure APIs with OAuth2/JWT
✔ Limit CORS access to trusted domains
✔ Implement rate limiting for API protection
✔ Encrypt passwords before storing
Keywords
Spring Boot security, REST API security, Spring Security best practices, secure microservices, OAuth2 authentication, JWT authentication, API security.
Comments
Post a Comment
Leave Comment