BEST PRACTICES TO SECURE
WEB APPLICATIONS
Ronak Hingonia
IIT Gandhinagar
ronakhingonia1@gmail.com
I. INTRODUCTION
This document is intended for students and professional developers as a quick reference checklist for security
practices. It covers 11 categorized security aspects that, when implemented, can help prevent the corresponding
attacks. A before-and-after code example is then presented to demonstrate what secure code looks like in Ex-
press.js for easier understanding. Finally, a table lists the top open-source security tools every developer should
know.
II. KEY TERMS
Authentication, Authorization, Encryption, Firewall, Web Application, Vulnerability, Attack
III. DEFINITIONS
1. Authentication: The process of verifying the identity of a user or system.
2. Authorization: The process of restricting user access to resources based on roles or permissions, ensuring
that users can only perform actions within their privileges.
3. Encryption: The technique of converting information into a secure format.
4. Firewall: A network security system that monitors and controls incoming and outgoing traffic.
5. Web Application: A software application that runs on a web server and is accessed via a web browser.
6. Vulnerability: A weakness in a system that can be exploited to cause harm.
7. Attack: An information security threat that involves an attempt to obtain, alter, destroy, remove, implant, or
reveal unauthorized information.
IV. ABBREVIATIONS
• SQL: Structured Query Language • OSS: Open Source Software
• XSS: Cross-Site Scripting • CI/CD: Continuous Integration / Continuous Deploy-
• MFA: Multi-Factor Authentication ment
• 2FA: Two-Factor Authentication • IDE: Integrated Development Environment
• RBAC: Role-Based Access Control • SBOM: Software Bill of Materials
• ABAC: Attribute-Based Access Control • CLI: Command-Line Interface
• TLS: Transport Layer Security • ZAP: Zed Attack Proxy
• HSTS: HTTP Strict Transport Security • OSV: Open Source Vulnerabilities
• DoS: Denial-of-Service • KICS: Keeping Infrastructure as Code Secure
• DTO: Data Transfer Object • OPA: Open Policy Agent
• CORS: Cross-Origin Resource Sharing • IaC: Infrastructure as Code
1
S CATEGORY DESCRIPTION IMPLEMENTATION/ PRACTICES PREVENTS FROM
No.
1 Authentication Verifies the identity of • Enforce multi-factor authentication • Unauthorized
users or systems to (MFA) or two-factor (2FA) access
ensure that only • Use secure hashing algorithms for • Identity spoofing
legitimate actors gain storing passwords • Brute force attacks
access to the application. • Integrate biometric or OTP
solutions
2 Authorization Restricts user access • Deny by default • Unauthorized
based on roles or • Never trust the request resource access
attributes, minimizing • Follow Least privilege • Role Explosion
damage from • Use role-based (RBAC) or attribute • Broken object level
compromised accounts. based access control (ABAC) Authorization
Critical for compliance (preferred) • Data breaches
and data integrity • Decouple from logic: use Custom • Misuse of system
security expressions functionality
• No hard-coding
• Secure APIs with token validation
(authentication)
3 Data Control Prevents Excessive Data • Create Data Transfer Objects • Property Level
Exposure—a (DTOs) issues
vulnerability where more • Least privilege • Unauthorized
information than • Select only the fields that are safe disclosure of
necessary is sent to the and necessary for the client. sensitive data
client, inadvertently • A mapper library can be used
exposing sensitive data. instead of manually created DTOs.
This type of problem is
often framed as Broken
Object Property Level
Authorization (BOPLA)
4 Input Ensures that • Never trust the request • SQL Injection
Validation user-provided data • Validate type, length, format, and • XSS (cross-site
conforms to expected range scripting)
formats and rules before • Enforce Limits • Command
processing, preventing • Validate Strings (use regexp) injection.
malicious input from • Prefer allowed lists (deny by • Exceptions - might
being processed by the deafault) expose the tech
application. • Validate Parameters stack being used in
• Should add the same validations on back end which
frontend as well can be then used
by a malicious
actor.
5 File Upload File uploads can be a • Scan the file first for viruses • Path traversal
significant security risk if • Never trust the request vulnerabilities
not handled correctly. • Use upload & download limits • Malware Injection
Attackers can upload • Do not trust the content type • Performance issues
malicious files that can headers because that can be altered • Remote code
compromise the security as well. execution
of the entire application • Validate the extension and type of
file
• Set file name length limit
• Always check for file MetaData
directly
2
S CATEGORY DESCRIPTION IMPLEMENTATION/ PRACTICES PREVENTS FROM
No.
6 Cross Origin Manages how web • Configure CORS policies to allow • Unauthorized
Resource applications can request only trusted domains cross-origin data
Sharing resources from a different • Use proper HTTP headers (e.g., access
domain, ensuring secure Access-Control-Allow-Origin) • Data leakage to
cross-origin • Restrict methods (e.g., GET, untrusted domains
communication. POST) and headers allowed in
cross-origin requests
• Avoid using wildcards (*) for
sensitive endpoints
• Implement preflight request
handling for complex requests
• Validate and sanitize incoming
cross-origin requests
7 Session Ensures secure handling • Use strong & random session IDs - • Session hijacking
Management of user sessions to prevent long and complex. • Session fixation
unauthorized access or • Implement session expiration and • Unauthorized
session hijacking. timeout policies Data access
• Regenerate session IDs after login or
performs any sensitive actions.
• Use HTTPS for session cookies
8 Rate Limiting Controls the frequency of • Use algorithms like token bucket, • Denial-of-service
client requests within a leaky bucket, fixed window, or (DoS) attacks
defined time frame to sliding window counters to control • Brute-force
protect application the flow of requests. attempts
resources from abuse and • Use Distributed Rate Limiting to • API abuse
overload ensure consistent enforcement across • Resource
multiple servers exhaustion
• Implement at multiple layers (API
gateway, load balancer, or web
server level)
9 Secure Com- Ensures data transmitted • Use HTTPS with strong TLS • Man-in-the-middle
munication between the client and configurations attacks
server is encrypted and • Enforce HSTS (HTTP Strict • Data interception
protected from Transport Security) • Eavesdropping
interception. • Disable weak ciphers and protocols
10 Web Acts as a protective • Deploy a WAF (hardware, software, • Automated attacks
Application barrier between the web or cloud-based) • Cross-site scripting
Firewalls application and incoming • Configure custom security rules and • SQL injection
(WAFs) traffic by filtering, anomaly detection • Denial of service
monitoring, and blocking
malicious requests based
on pre-defined security
rules.
11 Third-Party Manages risks associated • Regularly update third-party • Exploitation of
Dependencies with third-party libraries libraries library
and services used in the • Monitor for vulnerabilities in vulnerabilities
application. dependencies • Supply chain
• Use trusted sources for libraries attacks
• Limit permissions granted to
third-party services
3
Secure Coding Practices (JS)
This document outlines secure coding practices in JavaScript and Express by demonstrating
common security vulnerabilities and their corresponding solutions. Each example is presented
in a "before-and-after" format to highlight the transition from insecure to secure code.
• The rst code represents an insecure version with vulnerabilities, while the last code is its
secure, nalized version.
• Intermediate steps, if any, are shown with di erent themes are to illustrate the progression
toward secure implementation.
• Please go through the comments in code for explanation.
This visual approach is intended to make it easier to understand the security issues and how to
address them e ectively.
fi
fi
ff
ff
1. Authorization
Cons: checking what is not allowed
Cons: Role Explosion (for larger systems)
Pros: Deny by default
Cons: Broken Object Level Auth. - Can update any course as long as you know ID?
Pros: Custom security expression, No hardcoding
Cons: Database exploitation (no source of truth)
Pros: Least privilege, Deny by default
Final Code (tally from the database rst)
fi
2. Property Level Issues (Data Control)
Problems in the above code:
❌ Exposes passwords
❌ Reveals admin status
❌ Potential data misuse
Improvements:
✅ Passwords are no longer exposed
✅ Admin status is hidden, preventing privilege enumeration attacks
✅ Only necessary elds (id, name, email) are returned
✅ Prevents accidental data leaks in future updates
fi
3. Input Validation
Issues:
❌ No Input Validation – Allows any data type, length, or format.
❌ No Role Restriction – Any string can be used as a role.
❌ Potential DoS Attack Risk – Large or malformed inputs can overload the system.
Improvements
✅ Enums for Role Validation: Prevents arbitrary values.
✅ DTO for Input Validation: Enforces strict validation rules.
✅ Model for Data Structuring: Ensures consistency.
3.1 Parameters Validation
Issues:
❌ No Input Validation
❌ Denial of Service (DoS) Risk
❌ Excessive Data Exposure
Improvements
✅ Validated and Sanitized inputs with parameterized queries.
✅ Type Safety
3.2 SQL Injection
Injection Type-1:
Injection Type-2:
Final Code
● Why is this secure?
- The ? placeholder ensures that user input is properly escaped and treated as data, not
code.
- The database handles binding the parameter, preventing malicious injections.
- Even if an attacker tries admin' OR '1'='1, the query remains:
4. File Uploads
● Security Issues in the Above Code
1. Path Traversal: A user can upload a le with a name like ../../evil.sh, escaping the
upload directory.
2. No File Type Validation: Accepts any le type, including malicious ones.
3. No File Size Limit: Attackers can upload huge les to crash the server.
4. Trusting Content-Type Header: Easily spoofed by attackers.
5. No File Name Length Restriction: Very long lenames can cause issues.
Final Code
fi
fi
fi
fi
5. CORS (cross origin resource sharing)
❌ Allows all origins- risking unauthorized access
❌ Exposes highly data
❌ Lacks authentication
✅ Restricted Origins
✅ Limited Methods/Headers
✅ Authentication Check and Minimal Exposure
5 Open Source Security Tools
Developers Should Know
S Tool Result Quality DevX Customizability Maturity
No.
1 SemGrep OSS • 2000+ rules ported • Runs everywhere • Very extensible, Large
(Code scanner) from OSS tools (CLI, CI/CD, with many outputs Community of
(gitleaks, findsecbugs, Docker, IDE) formats active
gosec, more) • Very fast: no • Anyone can write contributors,
• Supports over 30+ compilation rules many years of
languages needed development
2 OSV-Scanner • Leverage OSV DB • Uses the OSV • Ability to scan Growing
(Dependency maintained by Google schema specific SBOM and popularity &
Checker) • Aggregates curated • Can run anywhere lockfiles Community
sources, i.e. Github (local, IDE, CI) • Multiple options
Security Advisories (ignore, recursive)
• Supports 13 Languages
3 KICS (IaC • Includes 2000+ queries • Provides 200+ • Queries written in Growing
Scanner) supporting 18 build-in OPA (Rego) popularity &
frameworks remediation • Ability to support community of
• Nightly Build recipes new frameworks contributors
• Curated rules with unit • Runs everywhere
tests (IDE plugin, local,
CI)
4 Trivy • Supports scanning • Fast, no setup or • Extensible through • High popularity
(Container container images, file prerequisites (i.e. modules (write • Large
Scanner) systems, git repos, Database or your own detection community
Virtual Machines, external libs) logic)
secrets, • Runs everywhere • Plugin to extend
IaC(Kubernetes, (IDE plugin, the CLI
Terraform) docker, local, CI)
• Can generate SBOM
5 ZAP (Runtime • Numerous features, • Runs everywhere • Extensible through • GitHub top
Scanner) detects the OWASP (docker, desktop extensions (100+ 1000 project
Top 10 risks app) available today) • Very popular &
• 250+ curated rules • Includes a headless • Plugins to extend large
mode to integrate the CLI community
in CI/CD pipeline • ZAP
Marketplace