---
url: "https://martinfowler.com/articles/web-security-basics.html"
titulek: "The Basics of Web Application Security"
h1: "The Basics of Web Application Security"
popis: "Security is both very important and often under-emphasized. While many targeted techniques help, there are some basic clean code habits which every developer can and should be doing"
jazyk: ""
kanonicka: ""
drobecky: []
zdroj: "live"
wayback_snapshot: ""
stazeno: "2026-09-13 22:06:10"
znaku: 102975
slov: 15840
kodovani: "windows-1250"
sha256: "9d63947d5ea271d077a4ebf7783c89fe9226a881367106e6a5d9a81d7d094b97"
---
# The Basics of Web Application Security
*Modern web development has many challenges, and of those security is both very
important and often under-emphasized. While such techniques as threat analysis are
increasingly recognized as essential to any serious development, there are also some
basic practices which every developer can and should be doing as a matter of course.*
05 January 2017
---
[Cade Cairns](https://github.com/cairnsc)
Cade Cairns is a software developer with a passion for security. He has experience
leading teams creating everything from enterprise applications to security testing
software, mobile applications, and software for embedded devices. At the moment his
primary focus is on helping improve how security concerns are addressed during the
solution delivery lifecycle.
[Daniel Somerfield](https://github.com/danielsomerfield)
Daniel Somerfield is a Technical Lead at Thoughtworks, where he works with
customers building systems that serve their business needs and are fast, flexible,
and secure. Daniel is an advocate for immutable infrastructure and cloud automation
as a vehicle to advance the state of secure agile delivery at Thoughtworks and in the
industry at large.
[programming style](/tags/programming%20style.html)
[security](/tags/security.html)
expand
## Contents
- Trust
- Reject Unexpected Form Input
- Untrusted Input
- Input Validation
- In Practice
- In Summary
- Encode HTML Output
- Output Risks
- Output Encoding
- Cautions and Caveats
- In Summary
- Bind Parameters for Database Queries
- Little Bobby Tables
- Parameter Binding to the Rescue
- Clean and Safe Code
- Common Misconceptions
- Parameter Binding Functions
- In Summary
- Protect Data in Transit
- HTTPS and Transport Layer Security
- Get a Server Certificate
- Configure Your Server
- Use HTTPS for Everything
- Use HSTS
- Protect Cookies
- Other Risks
- Verify Your Configuration
- In Summary
- Hash and Salt Your Users' Passwords
- Living Dangerously
- The Risks
- I Can Hash Passwordz
- A Dash of Salt
- Use A Hash That's Worth Its Salt
- Once More with Hashing
- Final Tips
- In Summary
- Authenticate Users Safely
- Understand Your Options
- Reauthenticate For Important Actions
- Conceal Whether Users Exist
- Preventing Brute Force Attacks
- Don’t Use Default Or Hard-Coded Credentials
- In Frameworks
- In Summary
- Protect User Sessions
- Generate Safe Session Identifiers
- Don't Expose Session Identifiers
- Protect Your Cookies
- Managing the Session Lifecycle
- Verify It
- In Frameworks
- In Summary
- Authorize Actions
- Authorize on the Server
- Deny by Default
- Authorize Actions on Resources
- Use Policy to Authorize Behavior
- Implementing RBAC
- Implementing ABAC
- Other Ways to Model Policy
- Implementation Considerations
- In Summary
### Sidebars
- About Argon2
---
The modern software developer has to be something of a swiss army knife. Of course,
you need to write code that fulfills customer functional requirements. It needs to be
fast. Further you are expected to write this code to be comprehensible and extensible:
sufficiently flexible to allow for the evolutionary nature of IT demands, but stable
and reliable. You need to be able to lay out a useable interface, optimize a database,
and often set up and maintain a delivery pipeline. You need to be able to get these
things done by yesterday.
Somewhere, way down at the bottom of the list of requirements, behind, fast, cheap,
and flexible is “secure”. That is, until something goes wrong, until the system you
build is compromised, then suddenly security is, and always was, the most important
thing.
Security is a cross-functional concern a bit like Performance. And a bit unlike
Performance. Like Performance, our business owners often know they need Security, but
aren’t always sure how to quantify it. Unlike Performance, they often don’t know
“secure enough” when they see it.
So how can a developer work in a world of vague security requirements and unknown
threats? Advocating for defining those requirements and identifying those threats is a
worthy exercise, but one that takes time and therefore money. Much of the time
developers will operate in absence of specific security requirements and while their
organization grapples with finding ways to introduce security concerns into the
requirements intake processes, they will still build systems and write code.
In this [Evolving Publication](/bliki/EvolvingPublication.html), we will:
- point out common areas in a web application that developers need to be particularly conscious of security risks
- provide guidance for how to address each risk on common web stacks
- highlight common mistakes developers make, and how to avoid them
Security is a massive topic, even if we reduce the scope to only browser-based web
applications. These articles will be closer to a “best-of” than a comprehensive
catalog of everything you need to know, but we hope it will provide a directed first
step for developers who are trying to ramp up fast.
## Trust
Before jumping into the nuts and bolts of input and output, it's worth mentioning
one of the most crucial underlying principles of security: trust. We have to ask
ourselves: do we trust the integrity of request coming in from the user’s browser?
(hint: we don’t). Do we trust that upstream services have done the work to make our
data clean and safe? (hint: nope). Do we trust the connection between the user’s
browser and our application cannot be tampered? (hint: not completely...). Do we trust
that the services and data stores we depend on? (hint: we might...)
Of course, like security, trust is not binary, and we need to assess our risk
tolerance, the criticality of our data, and how much we need to invest to feel
comfortable with how we have managed our risk. In order to do that in a disciplined
way, we probably need to go through threat and risk modeling processes, but that’s a
complicated topic to be addressed in another article. For now, suffice it to say
that we will identify a series of risks to our system, and now that they are
identified, we will have to address the threats that arise.
## Reject Unexpected Form Input
HTML forms can create the illusion of controlling input. The form markup author
might believe that because they are restricting the types of values that a user can
enter in the form the data will conform to those restrictions. But rest assured, it
is no more than an illusion. Even client-side JavaScript form validation provides
absolutely no value from a security perspective.
### Untrusted Input
On our scale of trust, data coming from the user's browser, whether we are
providing the form or not, and regardless of whether the connection is
HTTPS-protected, is effectively zero. The user could very easily modify the markup
before sending it, or use a command line application like curl to submit unexpected
data. Or a perfectly innocent user could be unwittingly submitting a modified version
of a form from a hostile website. [Same Origin Policy](https://en.wikipedia.org/wiki/Same-origin_policy)
doesn't prevent a hostile site from submitting to your form handling endpoint. In
order to ensure the integrity of incoming data, validation needs to be handled on the
server.
But why is malformed data a security concern? Depending on your application logic and use of output encoding,
you are inviting the possibility of unexpected behavior, leaking data, and even providing
an attacker with a way of breaking the boundaries of input data into executable code.
For example, imagine that we have a form with a radio button that allows the user
to select a communication preference. Our form handling code has application logic
with different behavior depending on those values.
```
final String communicationType = req.getParameter("communicationType");
if ("email".equals(communicationType)) {
sendByEmail();
} else if ("text".equals(communicationType)) {
sendByText();
} else {
sendError(resp, format("Can't send by type %s", communicationType));
}
```
This code may or may not be dangerous, depending on how the
`sendError` method is implemented. We are trusting that downstream logic processes untrusted content
correctly. It might. But it might not. We're much better off if we can eliminate the
possibility of unanticipated control flow entirely.
So what can a developer do to minimize the danger that untrusted input will
have undesirable effects in application code? Enter **input validation**.
### Input Validation
Input validation is the process of ensuring input data is consistent with application
expectations. Data that falls outside of an expected set of values can cause our
application to yield unexpected results, for example violating business logic,
triggering faults, and even allowing an attacker to take control of resources or the
application itself. Input that is evaluated on the server as executable code, such as a
database query, or executed on the client as HTML JavaScript is particularly dangerous.
Validating input is an important first line of defense to protect against this risk.
Developers often build applications with at least some basic input validation, for
example to ensure a value is non-null or an integer is positive. Thinking about how to
further limit input to only logically acceptable values is the next step toward reducing
risk of attack.
Input validation is more effective for inputs that can be restricted to a
small set. Numeric types can typically be restricted to values within a specific range.
For example, it doesn’t make sense for a user to request to transfer a negative amount
of money or to add several thousand items to their shopping cart. This strategy of limiting
input to known acceptable types is known as **positive validation** or
**whitelisting.** A whitelist could restrict to a string of a specific form
such as a URL or a date of the form “yyyy/mm/dd”. It could limit input length, a
single acceptable character encoding, or, for the example above, only values that are
available in your form.
Another way of thinking of input validation is that it is enforcement of the
contract your form handling code has with its consumer. Anything violating that
contract is invalid and therefore rejected. The more restrictive your contract,
the more aggressively it is enforced, the less likely your application is to fall prey
to security vulnerabilities that arise from unanticipated conditions.
You are going to have to make a choice about exactly what to do when input fails
validation. The most restrictive and, arguably most desirable is to reject it entirely, without
feedback, and make sure the incident is noted through logging or monitoring. But why
without feedback? Should we provide our user with information about why the data is
invalid? It depends a bit on your contract. In form example above, if you receive
any value other than “email” or “text”, something funny is going on: you either have a
bug or you are being attacked. Further, the feedback mechanism might provide the
point of attack. Imagine the sendError method writes the text back to the screen as an error message
like “We're unable to respond with `communicationType`“. That's all fine if the
communicationType is “carrier pigeon” but what happens if it looks like this?
```
```
You've now faced with the possibility of a reflective XSS attack that steals session
cookies. If you must provide user feedback, you are best served with a canned response that
doesn't echo back untrusted user data, for example “You must choose email or text”. If you
really can't avoid rendering the user's input back at them, make absolutely sure it's
properly encoded (see below for details on output encoding).
### In Practice
It might be tempting to try filtering the `