Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 40 ยท Trust, Security and Compliance

Securing an Online Shop

Secure a shop's code: sessions, price and quantity tampering, IDOR on orders, rate limiting, CSRF and XSS in checkout, admin hardening, secrets and dependency risk, with a live tamper demo.

A shop stores personal data, takes payments and moves goods, so it is a favorite target. The good news is that most successful attacks on shops are not clever. They exploit the same few mistakes: trusting data that came from the browser, forgetting to check who owns a record, leaving an admin panel open to the world, and running old software. This lesson walks through those mistakes and the habits that prevent them.

Fraud (stolen cards, chargebacks) is a different problem, covered in Fraud and Risk Management. Here we protect the application itself. The examples are platform neutral, and any framework offers built-in tools for most of the items below: use those before writing your own.

The golden rule: never trust the client

Everything that arrives from a browser is controlled by the person using it. They can edit a hidden field, replay a request with different numbers, or skip your JavaScript entirely. So the server must treat the request as a claim and recompute everything that matters:

  • Prices come from the catalog on the server, never from a field in the request.
  • Quantities are validated: an integer, at least 1, within a sensible maximum, and within available stock.
  • Discounts are recalculated from the coupon's rules on every request.
  • Totals, tax and shipping are computed from the server-side cart. The "total" sent by the browser is ignored (or compared only to detect a stale page).
  • Currency comes from the cart or order, not from a parameter.

A classic hole is an endpoint that accepts {"sku": "TS-100", "price": 0.01}. Another is a negative quantity: ordering -3 units can turn a charge into a credit. The validation lives next to the business rule, not in the form.

JS Price and quantity tampering

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The vulnerable function charges one cent to the cheater, and the negative quantity quietly cuts a 179.80 order down to 54.80 because the socks become a credit. The safe one ignores the client price and rejects bad quantities. Money in integers (see Representing Money Correctly) also removes a family of float tricks.

IDOR: checking who owns the record

IDOR (insecure direct object reference) is the most common serious bug in shops. The order page lives at /orders/1042. A logged-in customer changes the number to 1043 and sees someone else's name, address and items. The server found the order but never asked whether it belongs to the current user.

The fix is to include the owner in the lookup, in every place a record is read, changed or listed:

TEXT
SELECT * FROM orders WHERE id = :id AND customer_id = :current_user_id

If nothing is found, return the same "not found" response whether the order does not exist or belongs to someone else, so the response does not reveal which ids exist. Sequential ids make guessing easy, so use unpredictable ids or tokens for guest-facing links (for example the "view your order" link in an email), but treat that as an extra layer, not a replacement for the ownership check. The same applies to addresses, saved cards, invoices, return labels, and API endpoints used by the mobile app.

JS IDOR: with and without an ownership check

Press Run (or Ctrl + Enter) to see the console output here.

No output.

flowchart LR
    R["GET /orders/1043"] --> A{"Logged in?"}
    A -->|"no"| L["401: log in"]
    A -->|"yes"| O{"Order 1043 belongs<br/>to this user?"}
    O -->|"no"| N["404: not found"]
    O -->|"yes"| S["Show order"]

Authentication answers "who are you"; authorization answers "may you see this record".

Authentication and sessions

  • Hash passwords with a slow, salted algorithm (Argon2id or bcrypt) through your framework, never a fast hash such as plain SHA-256.
  • Rate limit logins and password resets per account and per IP, and respond the same way whether or not the email exists.
  • Regenerate the session id after login and on privilege changes, and clear it on logout.
  • Set cookies with Secure, HttpOnly and a SameSite value (Lax is a reasonable default), and give sessions a sensible lifetime.
  • Make reset and verification links single-use, random and short-lived.
  • Support two-factor authentication or passkeys, at least for admins.
  • Ask for the password again before sensitive changes such as email, password or payment methods.

Guest checkout needs care too: do not let a guest see another person's saved data just because the email address matches.

CSRF and XSS

CSRF (cross-site request forgery) tricks a logged-in user's browser into sending a request they did not intend, such as changing a delivery address, because the browser attaches cookies automatically. Defend with SameSite cookies and a CSRF token on every state-changing request (POST, PUT, PATCH, DELETE), and never change state with GET. Frameworks provide the token; make sure it is not disabled for "convenience" on checkout routes.

XSS (cross-site scripting) happens when attacker-controlled text is printed into a page as HTML. Shops have many such inputs: product reviews, questions, customer names, addresses, order notes, search queries, and also admin-visible fields (a "stored XSS" in a delivery note that runs when staff open the order is a path to admin takeover). Defenses:

  • Escape output for its context (HTML, attribute, JavaScript, URL). Template engines do this by default; be suspicious of every "raw" or "unescaped" output.
  • If you must allow formatted text, such as rich product descriptions, sanitize it with a maintained library using an allowlist of tags.
  • Send a Content Security Policy header that limits where scripts may load from. It is a safety net, not a substitute for escaping.
  • Load third-party scripts sparingly. A compromised analytics or chat script on the checkout page can steal card details. Prefer payment fields hosted by your provider (see PCI DSS Scope and 3-D Secure), and use Subresource Integrity or a tag manager with strict review for the rest.

Also prevent SQL injection by using parameterized queries or your framework's query builder everywhere, including sorting and filtering code.

Rate limiting and abuse

Besides login, protect: password reset and email sending (they can be used to spam others), coupon-code entry (guessing codes), gift-card balance checks, search, address autocomplete, and the payment attempt endpoint. A few requests per minute per IP and per account is plenty for humans. Return a 429 status with a Retry-After header, and combine limits with a CAPTCHA only where bots cause real harm. The velocity ideas in Fraud and Risk Management apply here too.

Make coupon codes long and random, and limit failed attempts, or attackers will enumerate them. Make sure a one-use coupon is consumed atomically, otherwise two parallel requests both succeed (see Reservations and Overselling for the same race condition on stock).

Hardening the admin

The admin panel can change prices, refund orders and export every customer. Treat it as the crown jewels:

  • Put it behind a separate path or host, and restrict it by IP or VPN where possible.
  • Require two-factor authentication for all staff.
  • Use roles with least privilege: support staff do not need export or price-editing rights.
  • Log administrative actions (who changed which price, who issued which refund) to an append-only audit log.
  • Alert on mass exports, many refunds and new admin users.
  • Remove accounts when people leave.

Secrets and configuration

API keys, database passwords, webhook secrets and signing keys must not be in source control or front-end bundles. Keep them in environment variables or a secret manager, use different values for development and production, restrict their permissions (a read-only reporting key should not be able to refund), and rotate them if they might have leaked. Payment provider secret keys never go to the browser; only the publishable key does. Verify incoming webhooks with their signature (Webhooks and Signature Verification) rather than trusting the sender's address.

Keep production errors quiet: show customers a generic page and send stack traces to your logs, not the response. Never write card numbers, full passwords or secrets to logs.

Dependencies and updates

A modern shop pulls in hundreds of packages, themes and plugins. Each is code that runs with your permissions. Common sources of breaches are an outdated platform or plugin with a known vulnerability, an abandoned extension, or a compromised package update. Habits that help:

  • Subscribe to security advisories for your platform and plugins, and apply security patches quickly.
  • Remove extensions you do not use. Fewer plugins means a smaller attack surface.
  • Pin versions with a lock file and review updates for packages that run at checkout.
  • Run automated dependency audits in CI, and keep backups that you have tested restoring.
  • Isolate the database and admin from the public internet, and keep the server and TLS configuration up to date.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A checkout request contains {"sku": "TS-100", "qty": 1, "price": 1}. How should the server handle the price?

    Any field from the browser can be edited, so the server must compute prices itself from trusted data.
  2. 2. A customer changes /orders/1042 to /orders/1043 and sees another person's order. What is this bug called?

    The server found the record but never checked that it belongs to the logged-in user. Include the owner in the lookup.
  3. 3. Which measure is the primary defense against stored XSS in product reviews?

    Escaping prevents the browser from interpreting user text as code. A Content Security Policy helps as a second layer.
  4. 4. Why should a password reset form respond the same way whether or not the email exists?

    Different responses let an attacker test lists of emails to find real customers. A neutral message hides that information.
  5. 5. Where should a payment provider's secret API key live?

    Secret keys can move money. They stay on the server, outside source control, and can be rotated if exposed.

Summary

  • Treat all browser data as untrusted: recompute prices, discounts, totals and currency on the server, and validate quantities.
  • Prevent IDOR by checking ownership on every read and write; return the same not-found response for missing and foreign records.
  • Protect sessions and logins with strong hashing, rate limits, secure cookies and two-factor authentication.
  • Use CSRF tokens, output escaping, a Content Security Policy and parameterized queries; keep third-party scripts out of checkout.
  • Rate limit logins, resets, coupons, gift-card checks and payment attempts.
  • Harden the admin with roles, two-factor, auditing and alerts; keep secrets out of code and logs.
  • Patch quickly, remove unused extensions and test your backups.

Next, the legal and ethical side of the data you hold: GDPR, Consumer Law and Accessibility.