Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 28 ยท Quality

Security, Sessions and Compliance

Secure a Salesforce B2C Commerce storefront: context-aware encoding against XSS, CSRF tokens, secrets, Business Manager roles, PCI scope, sessions and consent.

A store holds three things attackers want: money, personal data and the trust of shoppers. B2C Commerce takes care of a lot for you (the infrastructure, the network, the platform's own PCI compliance), but everything inside your cartridges is your responsibility. The platform cannot know that the name field you print into a template is attacker-controlled, or that the log line you wrote contains a card number.

This lesson covers the issues that appear again and again in storefront code: cross-site scripting (XSS) and output encoding, CSRF, injection in queries, secrets, Business Manager permissions, sessions, PCI scope and privacy. For the general e-commerce principles behind them, see Shop Security, PCI Scope and 3-D Secure and Privacy and Compliance. The platform code below is read-only. The TryIt blocks are stand-ins: plain JavaScript that reproduces the mistakes and the fixes so you can see them, using encoders written for this lesson (they are not the platform's encoders).

Cross-site scripting and encoding

XSS happens when text controlled by a user reaches a page as markup or script. The cure is output encoding: turn characters that are special in that place into harmless text. The key words are "in that place". HTML text, a quoted attribute, an unquoted attribute, a JavaScript string and a URL all have different special characters, so one encoder cannot serve all of them.

In ISML, isprint has an encoding attribute for exactly this:

HTML
<h1><isprint value="${pdict.product.name}" encoding="htmlcontent"/></h1>
<input type="text" value="<isprint value="${pdict.query}" encoding="htmldoublequote"/>"/>
<script>var term = "<isprint value="${pdict.query}" encoding="jsattribute"/>";</script>
<a href="${URLUtils.url('Search-Show', 'q', pdict.query)}">Search again</a>

Common encoding names include htmlcontent (text between tags), htmlsinglequote and htmldoublequote (inside quoted attributes), htmlunquotedattribute, the JavaScript ones such as jshtml, jsattribute and jssource, uricomponent for URL parts, and off. The default for ${} output encodes for HTML content, which is only right inside HTML text. Look up the exact list and behavior for your platform release; the principle is what matters:

  • Pick the encoder by where the value lands.
  • Treat encoding="off" as a code smell. It is needed for trusted markup (a content asset, see Content Assets and Page Designer), never for request data, product attributes imported from outside, or customer-entered text.
  • Never build HTML in a script and print it with encoding off. Pass data to the template and let the template encode it (ISML Templates).
  • Build URLs with URLUtils, which encodes parameters, instead of concatenating strings.

JSON responses need the same care: res.json() sets the right content type, but if a front-end script then does element.innerHTML = response.message, the bug is in the script. Prefer textContent.

JS Stand-in: encoding bugs and their fixes

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

No output.

Cases 2 and 3 are the classic trap: the text encoder is right for case 1 and wrong for attributes, because it leaves quotes and spaces alone. Case 4 is a different trap: the text encoder does not escape the double quote, so the value still ends the JavaScript string and runs code. The fix escapes quotes, angle brackets and ampersands as \x sequences, which are safe inside a script string. Every context needs its own encoder.

A parameter such as ?return=/cart is convenient and dangerous: if you redirect to whatever the parameter says, an attacker can send shoppers from your domain to theirs (an open redirect), or to a javascript: URL. Accept only local paths, and prefer a fixed list of destinations. Encoding does not help here because the problem is the meaning of the value, not its characters.

CSRF

Cross-site request forgery tricks a signed-in shopper's browser into sending a state-changing request (change address, place order) from another site. The defense is a secret token that a forged request cannot know, tied to the session. SFRA gives you middleware for it:

JavaScript
'use strict';

var server = require('server');
var csrfProtection = require('*/cartridge/scripts/middleware/csrf');

server.get('EditAddress', csrfProtection.generateToken, function (req, res, next) {
    res.render('account/editAddress'); // the token is available as pdict.csrf
    next();
});

server.post('SaveAddress', server.middleware.https, csrfProtection.validateAjaxRequest, function (req, res, next) {
    // only reached when a valid token was sent
    next();
});

module.exports = server.exports();

In the form template you include the token as a hidden field named pdict.csrf.tokenName. Use validateRequest for normal form posts and validateAjaxRequest for JSON calls. Every POST that changes data should have the middleware (see Forms, Validation and CSRF), and a GET must never change state. The next stand-in shows why a session-bound, unguessable token defeats a forged request.

Node.js Stand-in: a session-bound CSRF token (Node crypto)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A forged request from another site has the shopper's cookie but not the token, so it fails. (The real platform's token format is its own; this stand-in only shows the idea.)

Injection in queries

Some APIs accept a query string, for example custom object searches. Use the placeholders and pass values as arguments, never concatenate user input into the query:

JavaScript
'use strict';

var CustomObjectMgr = require('dw/object/CustomObjectMgr');

// Good: the value is bound to {0}
var hits = CustomObjectMgr.queryCustomObjects('Subscription', 'custom.email = {0}', 'creationDate desc', email);

// Bad: the value becomes part of the query text
// CustomObjectMgr.queryCustomObjects('Subscription', "custom.email = '" + email + "'", null);

Secrets

  • Never commit credentials, API keys or dw.json files with passwords to a repository (see Setting Up Your Development Environment).
  • Store integration credentials in service credentials and secrets in password-type preferences in Business Manager, not in cartridge code, and read them at runtime (see Service Framework and Third-Party Integrations).
  • Headless storefronts keep API client secrets on the server side (the SSR or proxy layer), never in browser bundles; browsers use public client flows. See OCAPI and SCAPI.
  • Rotate anything that may have leaked, and use separate credentials per environment.

Business Manager roles and access

Business Manager is the control panel for the whole business, so protect it as such. Users are managed centrally in Account Manager, where they get roles; a role grants functional permissions (which modules and actions) for an instance or specific sites. Apply least privilege: merchandisers do not need code deployment or administration modules, and developers rarely need production data. Use single sign-on and multi-factor authentication where your organization supports them, remove accounts when people leave, and review roles regularly. API clients get their own limited permissions too (see OCAPI and SCAPI).

Sessions

A shopper's session is identified by a cookie that the platform sets. Keep the following in mind:

  • Serve all storefront pages over HTTPS; routes that handle personal or payment data should use server.middleware.https.
  • Session data is stored on the server, but anything you put in a custom session attribute is held for the life of the session: do not keep secrets or large objects there.
  • Pages in the page cache are shared (see Caching and Performance); user-specific output must never be rendered into them.
  • Registered and guest shoppers differ in what they may do; check customer.authenticated on every protected route instead of hiding links (Customers, Sessions and Profiles).

PCI scope

The platform is certified for card data handling, but your site is only as compliant as its design. The safest rule is to keep card numbers out of your code entirely: use a payment provider's hosted fields or redirect so the card number goes from the browser to the provider, and your cartridge only receives a token and display data such as brand and last four digits. Do not log card data, do not put it in custom attributes, URLs or e-mails, and do not copy production payment data into sandboxes. If your integration touches card numbers, your PCI burden grows sharply. Background: PCI Scope and 3-D Secure.

Privacy laws such as the GDPR expect you to collect only what you need, tell shoppers what you collect, ask for consent where required and honor deletion and access requests. In B2C Commerce:

  • The base storefront has consent tracking middleware and a banner flow, and the choice is stored in the session; analytics and marketing scripts must wait for it.
  • Deleting a customer profile removes personal data, but orders and legal records have retention rules: decide with your legal team what is removed, anonymized or kept.
  • Keep personal data out of logs, custom caches and cached pages.
  • Document where each personal field lives so a deletion request can actually be completed.

More background is in Privacy and Compliance.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is encodeText (escaping only &, < and >) not enough for a value inside value="..."?

    Inside a quoted attribute, the quote character is special. An encoder for HTML text does not handle it, so the attribute context needs its own encoding.
  2. 2. When is encoding="off" acceptable in an ISML isprint?

    Off means the value is printed as raw markup. That is only safe for content that trusted staff author, never for input from shoppers or outside systems.
  3. 3. What does a CSRF token protect against?

    A forged request carries the cookie automatically but cannot know the secret token, so the server rejects it.
  4. 4. What is the safest approach to card data in your cartridge?

    Not touching card numbers keeps your PCI scope small. Tokens and masked display data are enough for orders, refunds and receipts.
  5. 5. Why should user input never be concatenated into a custom object query string?

    Concatenation lets the input become part of the query. Placeholders such as {0} keep data and query text separate.

Summary

  • Encode output for the context where the value lands; one encoder does not fit HTML text, attributes, JavaScript and URLs.
  • Use encoding="off" only for trusted staff content, and build URLs with URLUtils.
  • Validate redirect targets; accept only local paths or a fixed list.
  • Protect every state-changing POST with the CSRF middleware, and never change state on GET.
  • Bind query values with placeholders; never put secrets in code, repositories or logs.
  • Apply least privilege to Business Manager roles, and keep card data out of your cartridges.
  • Respect consent and retention rules, and keep personal data out of cached pages.
  • The TryIt blocks are stand-ins with their own encoders and token logic; the platform has its own implementations.

Next: Project: A Plugin Cartridge That Extends Checkout