Introduction
Web security is one of the most critical aspects of application development. Without proper safeguards, applications can be vulnerable to attacks such as Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and SQL Injection. In this post, we'll cover what these vulnerabilities are and how to mitigate them effectively.
1. Cross-Site Scripting (XSS)
What is XSS?
XSS is an attack where malicious scripts are injected into webpages viewed by other users. These scripts can steal session cookies, redirect users to malicious sites, or deface the website.
How to Prevent XSS?
✅ Escape User Input:
Use proper encoding to prevent execution of injected scripts.
const sanitizedInput = encodeURIComponent(userInput);
✅ Use a CSP (Content Security Policy):
A CSP restricts which scripts can be executed on your site.
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com;
✅ Validate and Sanitize Input:
Use libraries like DOMPurify to sanitize input:
import DOMPurify from 'dompurify';
const cleanHTML = DOMPurify.sanitize(userProvidedHTML);
✅ Avoid Inline JavaScript:
Don't use inline JavaScript like:
<button onclick="alert('Hello!')">Click me</button>
Instead, move scripts to external files.
2. Cross-Site Request Forgery (CSRF)
What is CSRF?
CSRF tricks an authenticated user into submitting a request to a web application without their consent. This can be used to change account settings, transfer funds, or perform other actions on behalf of the victim.
How to Prevent CSRF?
✅ Use CSRF Tokens:
Generate and validate CSRF tokens for form submissions.
// Example in NestJS
generateCsrfToken() {
return crypto.randomBytes(32).toString('hex');
}
✅ Use SameSite Cookies:
Set SameSite
attribute to Strict
or Lax
to prevent unauthorized cross-origin requests.
Set-Cookie: sessionid=abc123; HttpOnly; Secure; SameSite=Strict;
✅ Verify Referer Headers:
Check that requests originate from trusted sources.
if (!req.headers.referer.startsWith("https://yourdomain.com")) {
throw new Error("Invalid request");
}
3. SQL Injection
What is SQL Injection?
SQL Injection occurs when an attacker injects malicious SQL queries into an input field to manipulate the database.
How to Prevent SQL Injection?
✅ Use Prepared Statements:
// Example in NestJS using Knex.js
await knex.raw('SELECT * FROM users WHERE email = ?', [userEmail]);
✅ Use ORM (Object-Relational Mapping) Libraries:
ORMs like TypeORM and Prisma automatically handle query sanitization.
const user = await userRepository.findOne({ where: { email: userInput } });
✅ Validate and Sanitize Input:
Use input validation libraries like Joi or Zod:
import * as Joi from 'joi';
const schema = Joi.object({
email: Joi.string().email().required()
});
✅ Limit Database Permissions:
Ensure that database users have the minimum required privileges to reduce impact if compromised.
Conclusion
Securing your web application against XSS, CSRF, and SQL Injection is essential to prevent unauthorized access and data breaches. By escaping user input, using CSRF tokens, and implementing prepared statements, you can significantly reduce security risks in your web applications.
Top comments (0)