Softellar

Insights · Engineering and quality

Web Security Best Practices: A Practical Guide for Web Applications

Practical web security best practices for every stage: secure coding, testing, deployment, and monitoring, plus a pre-release checklist.

Kirill Bahdanovich

Head of Technology

29 min read

Published Updated

Audio brief

0:00 / 5:14

Overview

The application works. The tests are green, last quarter's vulnerability scan came back clean, and the release went out on time. A month later, a customer notices that changing the order number in the URL shows them someone else's invoice. No tool flagged it, because the code did exactly what it was written to do. It just never asked whether this user was allowed to see this order.

Web security best practices are the habits and controls, in code, configuration, and process, that protect a web application and its users' data at every stage of its life, from design to production. Most of them are unglamorous, and almost all of them are cheaper to apply early than to bolt on later.

This guide goes through them stage by stage: design, coding, testing, deployment, and operations. It also covers what to do first if your team has no dedicated security specialist, and it ends with a checklist you can run before each release.

Application Security and the Growing Attack Surface

Application security covers everything that decides whether a web application can be abused: the code your team writes, the third-party code it depends on, the configuration of servers and cloud services, the APIs it exposes, and even the scripts that run in the user's browser when your pages load. A weakness in any one of these can be enough.

The attack surface, meaning every place where someone can try to get in, has grown for most web applications over the past few years. A typical product now has a public API as well as a front end, several third-party integrations, a cloud setup with dozens of services, and a growing share of code that came from a package registry or an AI assistant rather than from someone on your team. Each of those has to be understood, secured, and kept up to date.

That's why securing web applications works through layers, not through a single control. A firewall won't fix a missing authorization check. A scanner won't tell you that a secret is sitting in a repository. Strong code won't help if the server around it is misconfigured. The practices below are meant to overlap, so that when one layer fails, another catches the problem.

Layered web application security across code, dependencies, configuration, APIs, and the browser
Securing web applications works through overlapping layers, not a single control

Why It Matters: Data Breaches, Customer Data, and Customer Trust

A web application is often the front door to the most valuable data a company holds: customer data, payment details, health records, internal documents. When that data leaks, the direct costs are only part of the damage. Regulators can impose fines, and GDPR in Europe and PCI DSS for anyone handling credit card data are the best-known examples. Customers have to be notified. Engineers spend weeks on investigation instead of building. And the customer trust that took years to earn can disappear in a single announcement.

Security failures also tend to be quiet. Nothing crashes, and there's no error that anyone reads in a log. A data breach can go unnoticed for a long time, sometimes until a third party points it out, which is one reason the monitoring practices later in this guide matter as much as prevention.

You don't need a security department to handle most of this. You need a short list of habits that the whole team follows, and the discipline to apply them to every release.

Web Security Best Practices for Design and Architecture

The cheapest security fixes are the ones made before anything is built. Design decisions, such as where data lives, who can reach it, and what happens when one component is compromised, are very hard to change later.

A lightweight form of threat modeling is enough for most teams. For each new feature, spend an hour on a few questions. What data does it touch? Who is supposed to access it? What could someone do with a stolen session, a leaked key, or a compromised dependency? Write the answers next to the design and turn the serious ones into tasks.

Two principles keep paying off. The first is secure defaults: new features start closed, with private data, minimal permissions, and no public endpoints, and are opened deliberately, not the other way round. The second is keeping the exposed surface small. If a service doesn't need to be reachable from the internet, it shouldn't be, and an admin interface rarely needs to sit on the same public address as the product.

Access Control by Design

Broken access control, where users can see or do things they shouldn't, tops the OWASP Top 10 and was the flaw behind the order example at the start of this article. A few rules prevent most of it:

  • Apply least privilege: users, services, and processes get only the access their job requires.
  • Check authorization on the server, on every request. Hiding a button in the interface is not access control.
  • Check ownership, not just identity. Being logged in doesn't mean the order belongs to you.
  • Prefer a central identity provider, using single sign-on through OpenID Connect or SAML, over a separate home-grown login in each application.

In ASP.NET Core, the ownership check from the opening example can be as small as this:

OrdersController.cs
[Authorize]
[HttpGet("orders/{orderId}")]
public async Task<IActionResult> GetOrderAsync(int orderId, CancellationToken cancellationToken)
{
    // Hypothetical helper that reads the ID from the authenticated identity
    var userId = User.GetUserId();

    var order = await database.Orders
        .FirstOrDefaultAsync(orderEntity => orderEntity.Id == orderId && orderEntity.CustomerId == userId, cancellationToken);

    return order is null ? NotFound() : Ok(order);
}

The query filters by the current user, so a changed ID in the URL finds nothing. Returning "not found" instead of "forbidden" also avoids confirming that someone else's order exists. This is a sketch: it assumes authentication is already configured and that GetUserId() is a helper of your own, so adapt both to your project.

Secure Coding Practices for Application Development

Many vulnerabilities that reach production come from ordinary code written under time pressure. These secure coding practices cover the areas where we see the most problems in application development.

Validate Input, Encode Output

Treat everything that comes from the client as untrusted: form fields, query strings, headers, cookies, uploaded files, and API payloads. Validate input on the server for type, length, format, and allowed values. Prefer an allowlist, which describes what is valid, over a denylist that tries to list everything dangerous, because denylists are easy to get around. Client-side validation helps users, but it can't be relied on for protection, since attackers can send requests to your server directly.

Validation alone doesn't stop injection attacks. Against SQL injection, use parameterized queries or an ORM and never build SQL by concatenating strings:

Queries.cs
// Unsafe: user input becomes part of the SQL text
var query = "SELECT * FROM Users WHERE Email = '" + emailAddress + "'";

// Safe: the value travels as a parameter
var normalizedEmail = emailAddress.Trim().ToLowerInvariant();
var user = await database.Users.FirstOrDefaultAsync(userEntity => userEntity.Email.ToLower() == normalizedEmail, cancellationToken);

Against cross-site scripting, the defense is encoding output for the place where it lands: HTML, an attribute, a URL, or JavaScript. Modern frameworks do this by default. Razor encodes output, and React escapes values rendered in JSX. The danger sits in the escape hatches, such as Html.Raw in Razor and dangerouslySetInnerHTML in React. Treat every use of them as a review item, and if content really must contain HTML, sanitize it with a maintained library first.

Authentication and Multi-Factor Authentication

Store passwords only as hashes produced by a slow, purpose-built algorithm such as Argon2, bcrypt, or PBKDF2. Hashing is not encryption: a hash can't be reversed, which is exactly the point. The current revision of NIST guidance (SP 800-63B, revision 4, finalized in 2025) favors long passwords over complexity rules, checking new passwords against lists of known leaked ones, and not forcing periodic changes without a reason. Treat it as a reference point: the right policy, including how strong the second factor must be, depends on how sensitive your application is.

Multi-factor authentication, often called two-factor authentication when it uses exactly two factors, should be mandatory for administrators and for any system holding sensitive data, and offered to every user. Not all second factors are equal. Codes from an authenticator app are better than SMS, and hardware keys and passkeys (FIDO2) also resist phishing, which one-time codes do not. Keep SMS as a fallback, not the default.

To slow down brute force attacks, rate-limit login attempts per account and per IP address, add progressive delays, and alert on spikes in failures. Hard lockouts alone can be turned against your real users, so prefer delays and alerts.

Sessions and CSRF

Send session cookies with the Secure, HttpOnly, and SameSite flags, keep idle timeouts reasonable for the sensitivity of the data, and invalidate the session on the server at logout. Cross-site request forgery (CSRF) is a risk wherever the browser attaches credentials automatically, which is the case with cookie-based authentication. There, use the framework's anti-forgery tokens on state-changing requests; SameSite cookies are a useful baseline, not a complete answer. An API that authenticates with a bearer token in the Authorization header has a different threat model. The browser doesn't add that header on its own, so classic CSRF is less of a concern, and protecting the token from theft through XSS and configuring CORS carefully matter more.

Program.cs
builder.Services.ConfigureApplicationCookie(cookieOptions =>
{
    cookieOptions.Cookie.HttpOnly = true;
    cookieOptions.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    cookieOptions.Cookie.SameSite = SameSiteMode.Lax;

    cookieOptions.ExpireTimeSpan = TimeSpan.FromMinutes(30);
    cookieOptions.SlidingExpiration = true;
});

Keep Secrets Out of the Code

Passwords, API keys, connection strings, tokens, and certificates don't belong in source code, in configuration files committed to the repository, or in chat messages. Use a secrets manager such as Azure Key Vault, AWS Secrets Manager, or HashiCorp Vault, give each environment its own secrets, and rotate them on a schedule and whenever someone with access leaves. Add a secret scanner to the pipeline and to pre-commit hooks so an accidental commit is caught early. A secret that was ever committed should be treated as compromised, even if the next commit deletes it: rotate it.

Third-Party Code and Dependencies

A large share of a modern application is code someone else wrote. Keep an inventory of your dependencies, including indirect ones, in the form of a software bill of materials (SBOM). Run software composition analysis (SCA) in CI/CD and block the build on serious vulnerabilities that are exploitable in your context, sending lower-severity findings to a backlog with deadlines, pin versions with lockfiles, update regularly with testing, and remove packages you no longer use. Before adding a new package, look at who maintains it, how active it is, and whether its name is a near-copy of a popular one. OWASP gave this area its own category, Software Supply Chain Failures, in the 2025 edition of its Top 10.

Third-party scripts in the browser, such as analytics, chat widgets, and payment forms, run with the same privileges as your own code. Load only what you need and protect them with a content security policy and, where the files are static, Subresource Integrity, covered in the deployment section below.

Handle Errors Safely

Show users a generic message and log the details on the server. Stack traces, SQL errors, and framework versions in a response are a gift to an attacker. Make failures fail closed: if an authorization check throws an exception, the request should be denied, not allowed through. OWASP's 2025 list includes Mishandling of Exceptional Conditions as a category for exactly this reason. Disable debug endpoints and detailed error pages in production.

AI-Generated Code

Code suggested by an AI assistant needs the same review and the same automated checks as code written by a person. It can look polished while missing an authorization check, using an outdated API, or pulling in a dependency that doesn't exist or isn't what its name suggests. Put it through the same pipeline and hold it to the same standard.

Security Testing: Automated Tools, Audits, and Penetration Testing

Functional tests prove that the application does what it should. Security testing asks a different question: what can someone make it do that it shouldn't? A suite of green functional tests says very little about that, which is why security checks need their own place in the pipeline.

Four kinds of checks cover most of the ground, and they find different things.

CheckWhat it examinesWhen to run itWhat it findsWhat it misses
SAST (static analysis)Source codeOn every pull requestInjection patterns, hard-coded secrets, unsafe API useProblems that appear only at runtime or in configuration
SCA (composition analysis)DependenciesOn every build, plus a scheduled scanKnown vulnerable librariesFlaws in your own code, and vulnerabilities nobody has reported yet
DAST (dynamic testing)The running applicationAgainst a test environment, on merge or nightlyMisconfiguration, missing headers, some injection and authentication flawsCode paths the scanner can't reach, and most business logic flaws
Penetration testThe whole system, tested by peopleAt least yearly and after major changesChained attacks and business logic flaws that tools don't seeAnything that changed after the test
Comparison of SAST, SCA, DAST, and penetration testing for web applications
Four kinds of security checks find different problems at different stages

Automated tools belong in CI/CD, where a developer gets feedback while the change is still fresh. Open-source options exist for each type, such as ZAP for dynamic scanning and Dependabot or OWASP Dependency-Check for dependencies. To avoid slowing the team down, start with a small set of high-confidence rules, fail the build only on serious findings, and keep the rest as a visible backlog. A scanner that produces hundreds of false alarms tends to get ignored and, eventually, switched off.

Vulnerability assessment and penetration testing are often confused. An assessment is a broad, mostly automated search for known weaknesses. A penetration test is a person trying to break in the way an attacker would, including by abusing business logic, as in the order example at the start of this article. Both have a place, and the second finds what tools can't.

As a baseline, run a penetration test at least once a year and after significant changes to architecture or authentication. Regulations, customer contracts, and cyber insurance providers sometimes require more.

Finally, add security to code review. A short checklist, asking whether every endpoint checks authorization, whether input is validated, and whether the change adds a dependency or a secret, catches many problems before they reach testing. Security testing is also separate from QA: test engineers verify that features work, while security testers look for what shouldn't work.

Secure Deployment and Infrastructure

A secure application can still be exposed by the way it's deployed. This stage is mostly about configuration, which makes it easy to get wrong and easy to automate.

Encrypt Traffic and Data

Use TLS 1.2 or newer, preferably 1.3, disable older protocol versions, redirect all HTTP traffic to HTTPS, and automate certificate renewal so an expired certificate never takes you down. Add the HSTS header so browsers refuse to reach your site over plain HTTP. Inside your network, hold traffic between services to the same standard. Encrypt sensitive data at rest as well, in databases, backups, and file storage, using your platform's managed encryption and keeping the keys in a key vault, not next to the data.

Security Headers

Headers let your server tell the browser how to treat your content. The snippet below is a minimal illustration, not a production configuration. That CSP, for example, would block inline scripts and styles and any resources from other domains until you adjust it for your application:

Program.cs
app.UseHsts();

app.Use(async (httpContext, next) =>
{
    httpContext.Response.Headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self'; frame-ancestors 'none'";
    httpContext.Response.Headers["X-Content-Type-Options"] = "nosniff";
    httpContext.Response.Headers["Referrer-Policy"] = "strict-origin-when-cross-origin";

    await next();
});

The content security policy (CSP) is the most powerful of these and the one that needs the most tuning. Start in report-only mode, see what breaks, then enforce. Subresource Integrity adds a second layer for scripts you load from other domains: an integrity attribute with the file's hash makes the browser refuse a file that has been altered. It only suits files whose content never changes under the same URL, so it doesn't fit scripts that a vendor updates in place. For those, rely on a tight CSP, load them from a source you trust, and review them regularly. MDN's web security documentation describes each header in detail.

Web Application Firewalls: What They Do and Don't Do

A web application firewall (WAF) sits between your application and its clients and inspects traffic at the application layer, layer 7 of the OSI model. It blocks patterns typical of SQL injection, cross-site scripting, and automated scanning. That sets it apart from network firewalls, which filter by address and port and know nothing about what's inside an HTTP request.

A WAF is a useful extra layer. It stops mass-scale attacks and can buy you time while you patch. It is not a substitute for secure code, and it can't see what happens in the user's browser, such as a tampered third-party script quietly copying payment details. A content security policy and, where it fits, Subresource Integrity help limit that risk.

Securing Cloud Computing Environments

Cloud providers secure the infrastructure; you secure what you put on it. This shared responsibility is where cloud incidents commonly start: storage left public, permissions far wider than needed, forgotten test environments. Give service accounts only the permissions they need, keep storage private by default, allow only the network traffic that has to flow, and define infrastructure as code so that configuration is reviewed like any other change and can be scanned for mistakes before it's deployed.

Protecting Against DDoS Attacks

Distributed denial-of-service attacks try to knock an application offline by overwhelming it. High-volume attacks are absorbed at the network level, which is the job of your cloud provider or a CDN, not of your own servers. At the application level, rate limiting, caching, and sensible limits on expensive operations such as search and report generation keep a flood of legitimate-looking requests from exhausting your backend. And write down what happens if an attack comes: who gets called, how traffic is rerouted, and how users are told.

Monitor and Analyze Web Traffic in Production

Prevention fails sometimes. How much damage follows depends on how quickly you notice and what you can do about it.

Start with logging. Record sign-ins and failed sign-ins, authorization failures, administrator actions, changes to permissions, and unusual validation errors. Just as important is what stays out of the logs: passwords, session tokens, API keys, and card numbers should never be written, and error details shown to users should be generic. Logs are a target too, so restrict who can read them and ship them off the application server, so an attacker can't erase their traces.

Logs only help if someone looks at them. Collect them in one place and set alerts on signals that mean something: a spike of failed logins from one address, a sudden rise in requests to a single API endpoint, access to admin routes from an unfamiliar country, large data exports at odd hours. To analyze web traffic usefully, you first need to know what normal looks like. Real-time monitoring then flags deviations from it, and continuous monitoring keeps working at 3 a.m., when nobody is watching.

Keep everything up to date. Operating systems, runtimes, frameworks, and libraries get security patches regularly, and attackers read the same advisories you do. Apply updates on a schedule, test them, and treat your oldest components as a risk, not a given. When a system has fallen too far behind to update safely, it may be time for modernizing the outdated application instead of patching around it.

Back up what you can't afford to lose. The 3-2-1 rule is a good starting point: three copies of your data, on two different types of storage, with one copy offsite. Add immutable copies that can't be changed or deleted for a set period, so that ransomware or a compromised account can't wipe your backups too. Then test restores regularly, because an untested backup is only a hope.

Finally, have an incident response plan before you need one. It can fit on a page: who leads, who gets called and in what order, how to isolate an affected system, how and when customers and regulators are told, and how you review what happened afterwards. The timelines can be tight. GDPR, for example, requires notifying the supervisory authority within 72 hours of becoming aware of a personal data breach, unless the breach is unlikely to put people's rights and freedoms at risk.

Where to Start: Security Priorities for Small Development Teams

If your team has no security specialist, the practices above can feel like too much at once. Don't try to do it all in a sprint. The order below is a suggestion, not a standard, and it rests on one idea: fix what is cheap and commonly exploited first, and build the rest into your routine.

WhenWhat to doWhy this comes first
Week 1Move secrets out of the code and rotate any that were exposed. Update dependencies with known serious vulnerabilities. Enforce HTTPS with HSTS. Check that a backup can actually be restored.Quick to do, and each item closes a gap that is easy to exploit
Week 2Add SAST and SCA to the CI pipeline. Turn on MFA for administrators and internal systems. Review who has access to production and to cloud consoles.Stops new problems from entering, and shrinks the damage from a stolen password
Months 1–2Add security headers. Set up logging and alerts for logins and admin actions. Check authorization on every endpoint that returns user data. Write a one-page incident plan.Gives you visibility and covers the most common serious flaw, broken access control
After thatThreat modeling for new features, DAST in the pipeline, and a first penetration testNeeds the basics in place to be worth the money
Security priority timeline for small development teams from week 1 through later months
A practical order for small teams: fix cheap, commonly exploited gaps first

Adjust the order to your own risks. A payment product should move the penetration test and the incident plan forward. A small internal tool with no sensitive data can reasonably take longer over some of the rest. The point is to have an order and to keep to it.

Web Application Security Best Practices Checklist

Copy this into your wiki or pull request template and run through it before each major release. Delete what doesn't apply, and add the items specific to your product.

Web Application Security Checklist

DESIGN

  • [ ] Threat model done for new features (data, who accesses it, what if it leaks)
  • [ ] New features closed by default; only necessary services are public
  • [ ] Authorization and object ownership checked on the server, on every request

CODE

  • [ ] Input validated on the server with allowlists
  • [ ] Queries parameterized; no SQL built from strings
  • [ ] Output encoded; every Html.Raw / dangerouslySetInnerHTML reviewed
  • [ ] Passwords hashed with Argon2, bcrypt, or PBKDF2
  • [ ] MFA enforced for admins and offered to users; login attempts rate-limited
  • [ ] Cookies Secure, HttpOnly, SameSite; CSRF protection on state-changing requests
  • [ ] No secrets in code or repository; secret scanner running
  • [ ] Generic error messages for users; debug endpoints off in production
  • [ ] AI-generated code reviewed like any other code

TEST

  • [ ] SAST and SCA run on every pull request; no open critical findings
  • [ ] DAST run against a test environment
  • [ ] Penetration test in the last 12 months or after a major change

DEPLOY

  • [ ] TLS 1.2+ only; HTTP redirects to HTTPS; HSTS enabled
  • [ ] Security headers set (CSP, X-Content-Type-Options, Referrer-Policy); SRI on static third-party scripts
  • [ ] Sensitive data encrypted at rest; keys in a key vault
  • [ ] Cloud permissions least-privilege; storage private by default
  • [ ] WAF and DDoS protection in front of public applications

OPERATE

  • [ ] Sign-ins, access failures, and admin actions logged (no secrets in logs); alerts set
  • [ ] Dependencies, runtimes, and operating systems patched on a schedule
  • [ ] Backups follow 3-2-1 with an immutable copy; restore tested
  • [ ] Incident response plan written; owners named

How These Practices Map to the OWASP Top 10:2025

The OWASP Top 10 is the standard awareness list of critical web application security risks, and the 2025 edition changed it noticeably: supply chain failures and the handling of exceptional conditions are now categories of their own. The table shows which practices in this guide address each risk, so you can check your coverage at a glance.

OWASP Top 10:2025Where this guide addresses it
A01 Broken Access ControlAccess control by design, ownership checks, least privilege
A02 Security MisconfigurationSecure deployment, security headers, cloud configuration as code, debug endpoints off
A03 Software Supply Chain FailuresDependency inventory and SBOM, SCA in CI/CD, pinned versions, secret scanning
A04 Cryptographic FailuresTLS and HSTS, encryption at rest, key vault, password hashing
A05 InjectionServer-side validation with allowlists, parameterized queries, output encoding
A06 Insecure DesignThreat modeling, secure defaults, small exposed surface
A07 Authentication FailuresPassword hashing, multi-factor authentication, rate limiting, session handling
A08 Software or Data Integrity FailuresSubresource Integrity, pinned dependency versions, reviewed changes
A09 Security Logging and Alerting FailuresLogging, alerts, continuous monitoring, incident response plan
A10 Mishandling of Exceptional ConditionsSafe error handling, failing closed, debug endpoints off

For a risk-by-risk walkthrough with examples, see our article on handling the top 10 web application security risks.

The Bottom Line

Web application security isn't a product you buy or a project you finish. It's a set of habits: design with an attacker in mind, write code that doesn't trust its input, test for what shouldn't work, deploy with sensible defaults, and watch what happens in production. No single layer is enough, which is why the layers work together. If you're unsure where to begin, follow the order in the priorities section, fix what is cheap and commonly exploited, and keep going from there.

If you'd like a second opinion on your own application, our security consulting team is happy to take a look. Talk to our team

Written by

Kirill Bahdanovich

Head of Technology

More guides by Kirill

Share this guide

Filed under

  • Engineering and quality
  • Web Security
  • Web Development
  • Cybersecurity
  • Web Security Best Practices
  • Application Security
  • Secure Coding
  • OWASP Top 10
  • Penetration Testing
  • SAST
  • DAST
  • Web Application Firewall
  • Security Headers
  • Multi-Factor Authentication

Frequently Asked Questions

Find answers to common questions about this topic

Have a different question? Talk to our team

Need a Second Opinion on Your Application Security?

If you'd like a second opinion on your own application, our security consulting team is happy to take a look. We'll help you prioritize fixes across code, configuration, and your pipeline.

We reply within 24 hours and can sign an NDA first.

Have files or a long brief? Use the full form

  • Engineering and quality

    Handling the Top 10 Web Application Security Risks (OWASP)

    Web application security safeguards business reputation and customer trust. This guide reveals how development teams implement proactive measures against OWASP Top 10 vulnerabilities.

    Kirill BahdanovichHead of Technology

    9 min read10 min audio brief

    Read the guide
  • Engineering and quality

    React Single Page Application: How It Works and When to Use It

    Is React a single page application? Learn how a React SPA works, build a tested single page app with React Router, and see when the architecture fits.

    Kirill BahdanovichHead of Technology

    25 min read22 min audio brief

    Read the guide
  • Engineering and quality

    Server-Side Rendering in React: How It Works and When to Use It

    Learn how server-side rendering works in React: the request flow, hydration, streaming, a tested Next.js example, common pitfalls, and when SSR is worth it.

    Kirill BahdanovichHead of Technology

    25 min read25 min audio brief

    Read the guide

Ready to Put This to Work?

Tell us where security fits in your plans. An engineer will look at your situation and suggest a practical next step.

We reply within 24 hours, and we can sign an NDA before you share details.

Talk to the people who will scope your project