Interview question
What are security best practices for production Spring Boot applications? Production Spring Boot applications के लिए security best practices क्या हैं?
Answer
Use HTTPS, implement authentication/authorization, validate inputs, use parameterized queries, manage secrets, enable security headers, and keep dependencies updated. Follow OWASP top 10.
// 1. HTTPS Configuration
server:
ssl:
key-store: classpath:keystore.p12
key-store-password: ${SSL_PASSWORD}
key-store-type: PKCS12
key-alias: tomcat
// 2. Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.https()
.requiresChannel()
.anyRequest()
.requiresSecure()
.and()
.csrf().disable() // Use CSRF tokens
.headers()
.contentSecurityPolicy('default-src \'self\'');
}
}
// 3. Input Validation
@RestController
public class UserController {
@PostMapping('/users')
public ResponseEntity<?> createUser(@Valid @RequestBody UserRequest req) {
// @Valid ensures validation
// Never trust user input
}
}
public class UserRequest {
@NotBlank(message = 'Email required')
@Email(message = 'Valid email required')
private String email;
@Size(min = 8, message = 'Password min 8 chars')
private String password;
}
// 4. SQL Injection Prevention
// Use JPA (parameterized queries automatically)
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query('SELECT u FROM User u WHERE u.email = ?1')
Optional<User> findByEmail(String email); // Parameterized
// NEVER do this:
// repository.find('SELECT * FROM users WHERE email = ' + email);
}
// 5. Secrets Management
spring:
datasource:
password: ${DB_PASSWORD} # From environment
jwt:
secret: ${JWT_SECRET}
// Or use Vault/AWS Secrets Manager
@Component
public class SecretProvider {
@Autowired
private VaultOperations vaultOps;
public String getDatabasePassword() {
return vaultOps.read('secret/data/db', String.class);
}
}
// 6. JWT Token Implementation
@Component
public class JwtTokenProvider {
@Value('${jwt.secret}')
private String jwtSecret;
public String generateToken(Authentication authentication) {
return Jwts.builder()
.setSubject(authentication.getName())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 86400000))
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
}
// 7. Dependency Updates
# Check for vulnerabilities
mvn dependency-check:check
// 8. Audit Logging
@Component
@Aspect
public class AuditLogAspect {
@Before('execution(* com.example.service.*.*(..))')
public void auditLog(JoinPoint joinPoint) {
// Log sensitive operations
logger.info('User: {}, Action: {}',
SecurityContextHolder.getContext().getAuthentication(),
joinPoint.getSignature().getName());
}
}
// 9. Rate Limiting
@Configuration
public class RateLimitConfig {
@Bean
public RateLimiter rateLimiter() {
return RateLimiter.create(100); // 100 requests/sec
}
}
// 10. Security Headers
spring:
security:
headers:
content-security-policy: 'default-src \'self\''
x-frame-options: DENY
x-content-type-options: nosniff
x-xss-protection: '1; mode=block'
// OWASP Top 10:
// 1. Injection
// 2. Broken Authentication
// 3. Sensitive Data Exposure
// 4. XML External Entities (XXE)
// 5. Broken Access Control
// 6. Security Misconfiguration
// 7. XSS
// 8. Insecure Deserialization
// 9. Using Components with Known Vulnerabilities
// 10. Insufficient Logging & MonitoringSecurity Best Practices:
1. HTTPS: SSL certificate configure करना
2. Authentication: JWT tokens use करना
3. Authorization: Role-based access control
4. Input Validation: @Valid, whitelist करना
5. SQL Injection: JPA use करना (automatic)
6. Secrets: Environment variables, Vault
7. Dependencies: mvn dependency-check करना
8. Audit Logging: Important operations log करना
9. Rate Limiting: DDoS protection
10. Security Headers: CSP, X-Frame-Options
OWASP Top 10:
- Injection attacks prevent करना
- Authentication properly implement करना
- Sensitive data encrypt करना
- Access control verify करना
- Logging & monitoring enable करना
Tools:
- OWASP ZAP scanner
- SonarQube
- Checkmarx
- SnykWas this answer clear?