DEV Community

Cover image for App Security: Common Attacks & How to Prevent Them
Shreyash Mishra
Shreyash Mishra

Posted on

App Security: Common Attacks & How to Prevent Them

Web applications are everywhere, from personal blogs to massive enterprise platforms, and they’re all potential targets for attackers. Securing them isn’t just a nice-to-have—it’s critical. Whether you’re a frontend developer, backend engineer, or full-stack pro, understanding the most common attacks and how to prevent them is essential to building robust apps. This guide breaks down the major threats, explains how they work, and shares practical ways to protect your applications.

Distributed Denial of Service (DDoS)

What It Is
A DDoS attack overwhelms your server with a flood of traffic, making it impossible for legitimate users to access your app. Think of it like a traffic jam that clogs up your server’s ability to function.

How to Prevent It

  • Use a Web Application Firewall (WAF), such as Cloudflare or AWS Shield, to filter malicious traffic.
  • Set up rate limiting and IP blacklisting to control excessive requests.
  • Enable auto-scaling and redundancy in your infrastructure to handle sudden spikes.
  • Monitor traffic patterns with tools like Grafana, Prometheus, or Datadog to spot attacks early.

Common Mistakes

  • Relying solely on your server’s resources without rate limiting, which leaves you vulnerable to brute-force attacks.
  • Not using a Content Delivery Network (CDN), which can expose your origin server to direct attacks.
  • Failing to monitor traffic, delaying your ability to detect and respond to an attack.

Cross-Site Scripting (XSS)

What It Is
XSS lets attackers inject malicious JavaScript into your web pages, which then runs in the browsers of unsuspecting users. It’s like planting a hidden trap that activates when someone visits your site.

Types

  • Stored XSS: The malicious script is saved on your server (e.g., in a database) and served to users.
  • Reflected XSS: The script is embedded in a URL or form input and reflected back in the response.
  • DOM-based XSS: The attack happens entirely in the browser via client-side scripts.

How to Prevent It

  • Escape all HTML, JavaScript, and URL outputs to neutralize harmful code.
  • Sanitize user input using libraries like DOMPurify.
  • Implement Content Security Policy (CSP) headers to restrict script sources.
  • Avoid using innerHTML— use textContent or safe templating engines instead.

Common Mistakes

  • Inserting user input directly into HTML without sanitizing it.
  • Using risky JavaScript functions like eval(), document.write(), or innerHTML.
  • Disabling browser XSS protections during development and forgetting to re-enable them.

Cross-Site Request Forgery (CSRF)

What It Is
CSRF tricks a logged-in user’s browser into sending unauthorized requests to a site where they’re authenticated. For example, an attacker might get a user to unknowingly transfer money or change their password.

How to Prevent It

  • Include unique CSRF tokens in forms to verify legitimate requests.
  • Set cookies to SameSite=Strict or Lax to limit cross-site misuse.
  • Use double-submit cookies for an extra layer of protection.
  • Never use GET requests for sensitive actions—stick to POST or other methods.

Common Mistakes

  • Skipping CSRF protection for internal APIs or admin routes, assuming they’re safe.
  • Using SameSite=None without HTTPS, which can expose cookies to attacks.
  • Relying only on cookies for security without validating tokens.

SQL Injection (SQLi)

What It Is
SQL injection happens when attackers sneak malicious SQL code into unsanitized inputs, letting them read, modify, or delete database data. It’s like giving an attacker the keys to your database.

How to Prevent It

  • Always use prepared statements or parameterized queries to safely handle inputs.
  • Never concatenate user input directly into SQL queries.
  • Validate and sanitize all user inputs, even for simple fields.
  • Use ORM frameworks like Django ORM or SQLAlchemy, which provide built-in protections.

Common Mistakes

  • Building SQL queries by stitching together user input (ex "SELECT * FROM users WHERE name='" + input + "'").
  • Not validating numeric or enum inputs, which can allow attackers to bypass logic.
  • Assuming ORMs are bulletproof—misusing raw query functions can still expose vulnerabilities .

CORS Misconfiguration

What It Is
Cross-Origin Resource Sharing (CORS) misconfigurations let malicious sites access sensitive data from your API by exploiting improper access controls.

How to Prevent It

  • Set Access-Control-Allow-Origin to specific, trusted origins instead of a wildcard (*).
  • Avoid enabling credentials (Access-Control-Allow-Credentials: true) unless necessary.
  • Test and validate CORS policies to ensure they’re not overly permissive.

Common Mistakes

  • Allowing CORS globally with Access-Control-Allow-Origin: *, even for sensitive endpoints.
  • Enabling credentials with wildcard origins, which browsers may block but attackers can exploit.
  • Misunderstanding how preflight requests work, leading to broken or insecure rules.

Server-Side Request Forgery (SSRF)

What It Is
SSRF tricks your server into making unauthorized requests, often to internal systems that should be off-limits, like metadata services or internal APIs.

How to Prevent It

  • Avoid letting user input dictate URLs unless absolutely necessary.
  • Validate and sanitize any URLs your app processes.
  • Block internal IP ranges (ex 169.254.169.254) in your firewall.
  • Use metadata filtering to prevent access to sensitive internal endpoints.

Common Mistakes

  • Fetching user-provided URLs without validation, opening the door to internal system access.
  • Allowing unrestricted file downloads or previews from arbitrary URLs.
  • Using third-party tools or libraries that make internal calls without proper safeguards.

Insecure Deserialization

What It Is
Attackers exploit serialized objects to execute malicious code when your server deserializes them, potentially taking over your system.

How to Prevent It

  • Don’t accept serialized objects from untrusted sources.
  • Use JSON instead of native serialization formats when possible.
  • Validate the structure of objects before deserializing them.
  • Add digital signature verification to ensure data integrity.

Common Mistakes

  • Trusting serialized data from clients, like cookies or tokens in binary formats.
  • Using outdated or vulnerable serialization libraries.
  • Not validating deserialized objects, which can allow arbitrary code execution.

Clickjacking

What It Is
Clickjacking tricks users into clicking hidden elements by embedding your site in an invisible iframe on a malicious page. It’s like setting a trap that looks like a legitimate button.

How to Prevent It

  • Set X-Frame-Options: DENY or SAMEORIGIN to block iframe embedding.
  • Use Content-Security-Policy: frame-ancestors 'none' for added protection.

Common Mistakes

  • Not setting frame-related headers, leaving your site open to embedding.
  • Allowing iframes on sensitive pages like login or payment forms.
  • Forgetting to test how your UI behaves when embedded elsewhere.

Man-in-the-Middle (MITM)

What It Is
An attacker intercepts communication between your users and your server, eavesdropping or altering data in transit.

How to Prevent It

  • Enforce HTTPS with HTTP Strict Transport Security (HSTS) headers.
  • Use strong TLS encryption for all connections.
  • Validate SSL certificates and avoid self-signed ones in production.

Common Mistakes

  • Supporting both HTTP and HTTPS, which can allow attackers to downgrade connections.
  • Skipping HSTS headers, making SSL stripping attacks easier.
  • Using weak or self-signed certificates, which attackers can exploit.

Broken Authentication

What It Is
Flaws in login or session management let attackers hijack user accounts, often by exploiting weak credentials or session handling.

How to Prevent It

  • Enforce strong password policies and encourage complexity.
  • Implement Multi-Factor Authentication (MFA) wherever possible.
  • Regenerate session tokens after login to prevent session fixation.
  • Use secure, HttpOnly, and SameSite cookies for session management.

Common Mistakes

  • Storing passwords in plaintext instead of hashing them with strong algorithms like bcrypt or scrypt.
  • Not invalidating sessions after logout or password changes.
  • Using predictable or short session tokens that are easy to guess.

Security Misconfiguration

What It Is
Default settings, open ports, or overly verbose error messages can expose sensitive information or leave your app vulnerable.

How to Prevent It

  • Disable unused services and debug logs in production.
  • Follow the principle of least privilege for all accounts and services.
  • Keep your server, database, and dependencies updated.
  • Use automated scanners like OWASP ZAP to catch misconfigurations.

Common Mistakes

  • Leaving debug mode enabled in production environments.
  • Exposing stack traces or file paths in error messages.
  • Running apps with unnecessary root or admin privileges.

API Abuse & Excessive Data Exposure

What It Is
Unsecured APIs can leak sensitive data or allow attackers to overload your system with excessive requests, leading to breaches or slowdowns.

How to Prevent It

  • Use API gateways to enforce throttling and rate-limiting.
  • Return only the data fields needed for each request.
  • Implement object-level and field-level access controls.
  • Log and monitor API usage to detect suspicious activity.

Common Mistakes

  • Returning full data objects, including sensitive fields like is_admin or password_hash.
  • Exposing internal API endpoints without proper authentication.
  • Not rate-limiting APIs, allowing bots or scripts to abuse them.

Bonus: Secure Development Practices

HTTP Security Headers
Add these headers to your server configuration for an extra layer of protection:

`Strict-Transport-Security: max-age=63072000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Referrer-Policy: no-referrer
Content-Security-Policy: default-src 'self'`
Enter fullscreen mode Exit fullscreen mode

Tools to Use

  • Static Analysis: Tools like Bandit or SonarQube to catch code-level issues.
  • Dependency Scanning: Run npm audit or pip-audit to check for vulnerable packages.
  • Dynamic Testing: Use OWASP ZAP or Burp Suite to test running applications.

Development Tips

  • Never expose sensitive files like .env, .git, or backups.
  • Integrate linting and static checks into your CI pipeline.
  • Rotate keys, tokens, and secrets regularly to minimize risks.

Conclusion
Building secure web applications isn’t a one-time task—it’s an ongoing commitment. Attackers only need one weak spot to cause havoc, so you have to stay vigilant and cover all bases. By following these best practices and weaving security into every stage of development, you can protect your users and your app. Stay proactive, keep learning, and code with confidence!

Top comments (0)