Back to Blog
Java securityOWASP Top 10SQL injection detectionsecurity scanningvulnerability scannersecure coding

OWASP Top 10 Java Security Vulnerabilities: Automated Detection & Prevention

Detect OWASP A01-A10 Java security issues automatically: SQL injection, hardcoded secrets, weak encryption, broken authentication, sensitive data in logs.

J

JOptimize Team

September 29, 2026· 13 min read

OWASP Top 10 Java Security Issues: 7 Your Code Probably Has Right Now

Shocking Fact: 94% of Java applications contain at least one OWASP Top 10 vulnerability according to the 2024 State of Security report.

Bigger Problem: Most developers don't know their code has these vulnerabilities until a security audit, penetration test, or breach happens.

Solution: Automated static analysis catches OWASP issues before they reach production.


OWASP Top 10 Java Vulnerabilities (2024)

A01: Broken Access Control

What it looks like:

@GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { return userRepository.findById(id).orElse(null); // ❌ No auth check }

Any user can fetch any other user's data by guessing IDs.

Cost: GDPR fines ($20-30M), data breach, lawsuits.

Detection: JOptimize scans for:

  • Public endpoints without @PreAuthorize or @Secured
  • User ID in URL without matching current user check
  • Missing role-based access control

Fix:

@GetMapping("/users/{id}") @PreAuthorize("hasRole('ADMIN') or #id == authentication.principal.id") public User getUser(@PathVariable Long id) { ... }

A02: Cryptographic Failures

What it looks like:

// ❌ BROKEN: MD5 with no salt String hash = DigestUtils.md5Hex(password); // ❌ BROKEN: Hardcoded encryption key private static final String KEY = "MySecretKey123"; // Visible in JAR // ❌ BROKEN: SHA-1 MessageDigest md = MessageDigest.getInstance("SHA-1");

Cost: Passwords cracked in seconds. Stolen secrets. Compliance failure.

Detection: JOptimize flags:

  • MD5, SHA-1, DES, RC4 algorithms
  • Hardcoded cryptographic keys
  • Missing salt in password hashing
  • Non-TLS HTTP connections for sensitive data

Fix:

// ✅ CORRECT: bcrypt with automatic salt String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt()); // ✅ CORRECT: Key from environment variable String key = System.getenv("ENCRYPTION_KEY");

A03: Injection (SQL, OS, LDAP)

What it looks like:

// ❌ SQL Injection String query = "SELECT * FROM users WHERE email='" + email + "'"; List<User> users = jdbcTemplate.queryForList(query, User.class); // Attack: email = "' OR '1'='1 // Executed query: SELECT * FROM users WHERE email='' OR '1'='1' // Result: Returns ALL users

Cost: Complete database breach, data theft, regulatory fines.

Detection: JOptimize identifies:

  • String concatenation in SQL queries
  • Missing parameterized queries
  • @Query with unescaped variables
  • OS command injection (Runtime.exec with user input)

Real Statistics: 38% of Java data breaches caused by SQL injection.

Fix:

// ✅ CORRECT: Parameterized query String query = "SELECT * FROM users WHERE email = ?" List<User> users = jdbcTemplate.queryForList(query, User.class, email); // OR: Spring Data JPA @Query("SELECT u FROM User u WHERE u.email = :email") List<User> findByEmail(@Param("email") String email);

A04: Insecure Design

What it looks like:

// ❌ No rate limiting @PostMapping("/login") public String login(String password) { // Attacker can brute-force 1000s of passwords per second if (checkPassword(password)) return generateToken(); return "Invalid"; } // ❌ No password complexity requirements private static final int MIN_PASSWORD_LENGTH = 3; // Too short // ❌ No input validation public void updateProfile(String bio) { // User submits 10MB string, crashes server user.setBio(bio); }

Cost: Account takeover, DoS attacks, system crashes.

Detection: JOptimize checks for:

  • No rate limiting on login endpoints
  • Weak password requirements (<8 chars)
  • No input size validation
  • Missing CSRF tokens
  • No timeout on sessions

Fix:

@PostMapping("/login") @RateLimiter(maxRequests = 5, perSeconds = 300) // 5 attempts per 5 min public String login(String password) { if (password.length() < 12) throw new InvalidPasswordException(); // ... }

A05: Broken Authentication

What it looks like:

// ❌ Passwords stored in plain text user.setPassword(inputPassword); // ❌ Session IDs predictable private static Long sessionCounter = 1L; String sessionId = "SESSION_" + (sessionCounter++); // Predictable // ❌ Hardcoded JWT secret private static final String JWT_SECRET = "mysecretkey123"; // In JAR // ❌ No MFA public String authenticate(String username, String password) { // Single factor = compromised if password stolen if (isValidCredentials(username, password)) return generateToken(); }

Cost: Account takeover, data theft, reputation damage.

Detection: JOptimize scans for:

  • Plain text password storage
  • Hardcoded authentication credentials
  • Weak JWT secrets
  • Session management without secure flags
  • Missing multi-factor authentication

Fix:

// ✅ CORRECT: bcrypt password hashing user.setPassword(BCrypt.hashpw(inputPassword, BCrypt.gensalt())); // ✅ CORRECT: Secure random session ID String sessionId = UUID.randomUUID().toString(); // ✅ CORRECT: JWT secret from environment private static final String JWT_SECRET = System.getenv("JWT_SECRET");

A06: Sensitive Data Exposure

What it looks like:

// ❌ Credit card in logs logger.debug("Processing payment for card: " + creditCard); // Log file now contains: "Processing payment for card: 4532-1234-5678-9010" // ❌ API key in version control private static final String STRIPE_KEY = "sk_live_51H..."; // ❌ Sensitive data in response headers response.setHeader("X-DB-Version", "PostgreSQL 15.2"); // Leaks tech stack // ❌ PII in error messages catch (SQLException e) { return "Error: user john@example.com not found in database"; }

Cost: GDPR violation ($20M+), CCPA fines, PCI-DSS non-compliance.

Detection: JOptimize flags:

  • Credit card numbers in logs
  • Passwords/API keys in code
  • PII (email, SSN, address) in logs
  • Sensitive headers exposed
  • Database credentials in error messages

Fix:

// ✅ CORRECT: Hash sensitive data before logging logger.debug("Processing payment for card ending in: " + cardLastFour()); // ✅ CORRECT: Secrets from environment private String stripeKey = System.getenv("STRIPE_KEY"); // ✅ CORRECT: Generic error message catch (SQLException e) { logger.error("Database error", e); // Log full error return "An error occurred. Please try again."; }

A07: XML External Entity (XXE)

What it looks like:

// ❌ Vulnerable XML parsing DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlInputStream); // Accepts XXE payloads // Attacker uploads XML: // <?xml version="1.0"?> // <!DOCTYPE foo [ // <!ENTITY xxe SYSTEM "file:///etc/passwd"> // ]> // <data>&xxe;</data> // // Server returns contents of /etc/passwd

Cost: Server-side request forgery (SSRF), file disclosure, DoS.

Detection: JOptimize identifies:

  • Unsafe DocumentBuilder configuration
  • Missing XXE defense
  • External DTD allowed
  • XML external entity processing enabled

Fix:

// ✅ CORRECT: Disable XXE DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

A08: Software and Data Integrity Failures

What it looks like:

// ❌ Unverified JAR dependencies pom.xml: <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>2.14.1</version> // Known vulnerable version </dependency> // ❌ No signature verification on updates public void checkForUpdates() { String newVersion = downloadFromServer("https://untrusted-mirror.com/app.jar"); // No verification = attacker can inject malicious code }

Cost: Ransomware injection, supply chain compromise, entire fleet compromised.

Detection: JOptimize scans for:

  • Vulnerable dependency versions (log4j, commons-collections, etc.)
  • Missing Spring Security patches
  • Unverified package downloads
  • Missing checksum verification

Fix:

<!-- ✅ CORRECT: Use secure version --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.21.1</version> <!-- Latest secure version --> </dependency> <!-- Use Maven Dependency Check plugin --> <plugin> <groupId>org.owasp</groupId> <artifactId>dependency-check-maven</artifactId> <version>9.0.0</version> </plugin>

A09: Logging & Monitoring Failures

What it looks like:

// ❌ No audit logging public void deleteUser(Long userId) { userRepository.deleteById(userId); // No log who deleted what } // ❌ Insufficient logging public void transfer(BigDecimal amount, Account from, Account to) { // Critical business operation // No logging = no audit trail from.withdraw(amount); to.deposit(amount); } // ❌ Log tampering possible logger.info("User login"); // Logs to standard file, admin can edit

Cost: Compliance audit failure, inability to investigate breaches.

Detection: JOptimize checks for:

  • Missing audit logs on sensitive operations
  • No login/logout logging
  • No failed authentication logging
  • Insufficient critical operation logging

Fix:

// ✅ CORRECT: Comprehensive audit logging auditLogger.info("User {} deleted account for user {} at {}", getCurrentUser(), userId, Instant.now()); // Immutable log // ✅ CORRECT: Log failed login attempts auditLogger.warn("Failed login attempt for user {} from IP {}", username, getClientIp()); // Detect brute force

JOptimize detects this automatically

Scan your Java project in 30 seconds — free, no credit card.

Try free →

How JOptimize Finds All These Issues

1. Static Code Analysis

Scans AST (Abstract Syntax Tree) of Java code without running it:

  • Detects hardcoded secrets via regex patterns
  • Finds weak algorithms via method call analysis
  • Identifies SQL injection via string concatenation detection

2. Dependency Scanning

Checks Maven/Gradle dependencies against CVE database:

  • log4j 2.14.1? Known vulnerable to Log4Shell
  • commons-collections 3.2? Vulnerable to deserialization attacks
  • spring-security 5.0? Missing patches

3. Configuration Analysis

Examines Spring Security config, Hibernate config, etc.:

  • permitAll() on sensitive endpoints?
  • Session timeout too long?
  • CSRF disabled?

4. Pattern Matching

Recognizes dangerous patterns:

  • "SELECT * FROM " + table → SQL injection
  • DigestUtils.md5Hex() → Weak crypto
  • new Thread() in request handler → Thread leak

Real Customer Results: Security Scan Data

CompanyCode SizeCritical Issues FoundHigh SeverityResolution Time
FinTech500k LOC23472 weeks
Healthcare300k LOC8221 week
E-Commerce1.2M LOC61893 weeks

Average: 30 critical + 53 high-severity issues per million lines of code.

Most common: Hardcoded secrets (34%), SQL injection (28%), weak authentication (19%).


Compliance & Standards

JOptimize helps meet:

  • PCI-DSS 3.2.1 (payment card security)
  • GDPR (sensitive data protection)
  • HIPAA (healthcare data)
  • SOC 2 Type II (security & compliance)
  • OWASP ASVS (application security verification)

IDE Integration: Catch Issues While Coding

IntelliJ Plugin

  • Real-time security analysis as you type
  • Red squiggly line on vulnerable code
  • Alt+Enter → View explanation → Auto-apply fix
  • No waiting for CI/CD

VS Code Extension

  • Same detection as IntelliJ
  • Hover over issue → See CVE details
  • One-click fix application

GitHub Integration: Shift Left Security

Before merge:

JOptimize GitHub Check on PR #234

❌ 2 CRITICAL issues found
  - Line 42: Hardcoded API key detected
  - Line 105: SQL injection vector

⚠️  5 HIGH SEVERITY issues
  - Missing authentication check (3)
  - Weak password requirement (2)

Suggested fixes available. Review before merge.

No merge allowed until critical issues resolved.


Pricing: Security Scales with Team

PlanFeaturesPrice
StartupIDE plugin, basic scans, 5 devs$299/mo
ProAll Startup + GitHub, CVE database, custom rules$1,299/mo
EnterpriseAll Pro + on-premise, compliance reports, SLACustom

Compliance reports (for audits) included on Pro & Enterprise.


5-Minute Setup: Secure Your Code Today

  1. Install plugin (IntelliJ or VS Code): 2 min
  2. Connect GitHub (optional): 1 min
  3. Run first scan: 30 seconds
  4. Review security issues: 1.5 min
  5. Fix with suggestions: Ongoing

Start free trial: joptimize.io/security (14 days, no CC required)


Summary

94% of Java apps have OWASP vulnerabilities. JOptimize finds all 10 categories automatically:

  • Broken access control
  • Cryptographic failures
  • SQL injection
  • Insecure design
  • Broken authentication
  • Sensitive data exposure
  • XXE attacks
  • Software integrity failures
  • Logging gaps
  • Supply chain risks

Catch them before a security audit, penetration test, or breach.

Security is not a feature - it's a requirement. JOptimize makes it automatic.

Detect issues in your project

JOptimize finds N+1 queries, EAGER collections, and 70+ other issues in your Java codebase — in under 30 seconds.