Based on the OWASP Top 10, comprehensively safeguard application security.
OWASP Top 10 (2021)
A01:2021 – Broken Access Control
Risk: Unauthorized users can access sensitive functionality or data
Mitigation Measures:
- ✓ Deny access by default, grant explicit authorization
- ✓ Implement role-based access control (RBAC)
- ✓ Disable directory listing
- ✓ Log and alert on access control failures
- ✓ Limit API access rate
Code Example:
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/users")
public List<User> getUsers() {
return userService.findAll();
}
A02:2021 – Cryptographic Failures
Risk: Sensitive data is unencrypted or uses weak encryption
Mitigation Measures:
- ✓ Use HTTPS to transmit all sensitive data
- ✓ Encrypt data at rest (databases, files)
- ✓ Disable weak encryption algorithms (MD5, SHA1)
- ✓ Use strong password hashing (bcrypt, Argon2)
- ✓ Key management (regular rotation, secure storage)
Code Example:
// 使用 BCrypt 加密密码
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String hashedPassword = encoder.encode(rawPassword);
A03:2021 – Injection
Risk: SQL injection, command injection, LDAP injection, etc.
Mitigation Measures:
SQL Injection Protection
// ❌ 不安全
String query = "SELECT * FROM users WHERE username = '" + username + "'";
// ✓ 安全:使用参数化查询
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, username);
NoSQL Injection Protection
// ✓ 使用参数绑定
Query query = new Query(Criteria.where("username").is(username));
Command Injection Protection
// ❌ 不安全
Runtime.getRuntime().exec("ls " + userInput);
// ✓ 安全:验证和转义
if (userInput.matches("[a-zA-Z0-9]+")) {
ProcessBuilder pb = new ProcessBuilder("ls", userInput);
pb.start();
}
A04:2021 – Insecure Design
Risk: Security flaws at the architecture and design level
Mitigation Measures:
- ✓ Threat modeling
- ✓ Secure design patterns
- ✓ Principle of least privilege
- ✓ Defense in depth
- ✓ Secure development lifecycle (SDLC)
A05:2021 – Security Misconfiguration
Risk: Default configurations, unupdated software, unnecessary features
Mitigation Measures:
- ✓ Minimize installation (remove unnecessary features)
- ✓ Disable default accounts and passwords
- ✓ Error messages do not expose sensitive information
- ✓ Regularly update and patch
- ✓ Security configuration review
Checklist:
# application.yml
server:
error:
include-stacktrace: never # 生产环境不暴露堆栈
spring:
devtools:
restart:
enabled: false # 生产环境禁用 devtools
A06:2021 – Vulnerable and Outdated Components
Risk: Use of libraries and frameworks with known vulnerabilities
Mitigation Measures:
- ✓ Remove unused dependencies
- ✓ Continuously monitor dependency vulnerabilities
- ✓ Obtain components from official sources
- ✓ Use signatures to verify component integrity
Tools:
# Maven 依赖检查
mvn dependency:tree
mvn versions:display-dependency-updates
# OWASP Dependency Check
mvn org.owasp:dependency-check-maven:check
A07:2021 – Identification and Authentication Failures
Risk: Weak passwords, improper session management, exposed credentials
Mitigation Measures:
Password Policy
- ✓ Minimum length of 8 characters
- ✓ Complexity requirements (uppercase and lowercase, numbers, special characters)
- ✓ Check for weak and commonly used passwords
- ✓ Limit the number of failed login attempts
- ✓ Multi-factor authentication (MFA)
Session Management
// Session 配置
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.maximumSessions(1)
.maxSessionsPreventsLogin(true);
return http.build();
}
A08:2021 – Software and Data Integrity Failures
Risk: Insecure CI/CD, automatic updates, deserialization
Mitigation Measures:
- ✓ Code signing
- ✓ CI/CD security hardening
- ✓ Dependency integrity verification
- ✓ Avoid insecure deserialization
// ❌ 不安全的反序列化
ObjectInputStream ois = new ObjectInputStream(inputStream);
Object obj = ois.readObject();
// ✓ 使用 JSON 等安全格式
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json, User.class);
A09:2021 – Security Logging and Monitoring Failures
Risk: Attacks cannot be detected and responded to
Mitigation Measures:
- ✓ Log all login and access control failures
- ✓ Audit logs for high-value transactions
- ✓ Standardize log formats
- ✓ Centralized log management
- ✓ Real-time alerts
Log Examples:
log.warn("Failed login attempt: user={}, ip={}",
username, request.getRemoteAddr());
log.info("Password changed: user={}, timestamp={}",
username, System.currentTimeMillis());
A10:2021 – Server-Side Request Forgery (SSRF)
Risk: Attackers control requests initiated by the server
Mitigation Measures:
- ✓ Prohibit user-controlled URLs
- ✓ URL whitelist
- ✓ Disable HTTP redirects
- ✓ Network layer isolation
// ✓ URL 验证
private boolean isAllowedUrl(String url) {
try {
URL u = new URL(url);
String host = u.getHost();
return ALLOWED_HOSTS.contains(host);
} catch (MalformedURLException e) {
return false;
}
}
Additional Security Measures
XSS Protection
// 输出转义
String safe = HtmlUtils.htmlEscape(userInput);
// Content Security Policy
response.setHeader("Content-Security-Policy",
"default-src 'self'; script-src 'self' 'unsafe-inline'");
CSRF Protection
// Spring Security 自动启用 CSRF
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
Clickjacking Protection
// X-Frame-Options
response.setHeader("X-Frame-Options", "DENY");
Security Response Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000; includeSubDomains
Content-Security-Policy: default-src 'self'
Sensitive Information Detection
Information That Should Not Be Hardcoded:
- ❌ Database passwords
- ❌ API keys
- ❌ Encryption keys
- ❌ Private key certificates
- ❌ OAuth secrets
Correct Practices:
# application.yml
spring:
datasource:
password: ${DB_PASSWORD} # 从环境变量读取
Secure Development Process
1. Requirements Phase
- Identify security requirements
- Threat modeling
2. Design Phase
- Secure architecture design
- Security design review
3. Coding Phase
- Secure coding standards
- Code review
4. Testing Phase
- Security testing
- Penetration testing
- Vulnerability scanning
5. Deployment Phase
- Security configuration check
- Least privilege deployment
6. Operations Phase
- Security monitoring
- Patch management
- Incident response
Recommended Tools
Static Analysis
- SpotBugs: Java code defect detection
- SonarQube: Code quality and security
- Checkmarx: Commercial static analysis tools
Dependency Checking
- OWASP Dependency-Check: Dependency vulnerability scanning
- Snyk: Open source dependency vulnerability detection
Dynamic Testing
- OWASP ZAP: Web application security testing
- Burp Suite: Penetration testing tools
Secret Scanning
- git-secrets: Prevent secret commits
- TruffleHog: Git history secret scanning
Security Checklist
Authentication and Authorization
- Implement a strong password policy
- Use multi-factor authentication
- Session timeout settings
- Secure password reset process
- Role-based access control
Data Protection
- HTTPS encrypted transmission
- Encrypted storage of sensitive data
- Secure key management
- Data masking
Input Validation
- Validate all input
- Parameterized queries to prevent SQL injection
- Output encoding to prevent XSS
- File upload validation
Security Configuration
- Disable unnecessary features
- Secure default configuration
- Error messages do not expose sensitive information
- Regularly update dependencies
Log monitoring
- Record security events
- Audit critical operations
- Anomaly alerts
- Log protection
Incident response
After discovering a vulnerability
- Assess impact: scope, severity
- Isolate systems: prevent further damage
- Fix the vulnerability: emergency patch
- Verify the fix: security testing
- Review and summarize: prevent recurrence