b2c-slas-auth-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

B2C SLAS Authentication Patterns

B2C SLAS 认证模式

Advanced authentication patterns for SLAS (Shopper Login and API Access Service) beyond basic login. These patterns enable passwordless authentication, hybrid storefront support, and system-to-system integration.
SLAS(Shopper Login and API Access Service)的高级认证模式,超越基础登录功能。这些模式支持无密码认证、混合店面部署以及系统间集成。

Authentication Methods Overview

认证方法概述

MethodUse CaseUser Experience
PasswordTraditional loginUsername + password form
Email OTPPasswordless emailCode sent to email
SMS OTPPasswordless SMSCode sent to phone
PasskeysFIDO2/WebAuthnBiometric or device PIN
Session BridgeHybrid storefrontsSeamless PWA ↔ SFRA
Hybrid AuthB2C 25.3+Built-in platform auth sync
TSOBSystem integrationBackend service calls
方法使用场景用户体验
密码传统登录用户名+密码表单
邮箱OTP无密码邮箱登录验证码发送至邮箱
短信OTP无密码短信登录验证码发送至手机
通行密钥FIDO2/WebAuthn生物识别或设备PIN码
会话桥接混合店面PWA ↔ SFRA 无缝切换
混合认证B2C 25.3+平台内置认证同步
TSOB系统集成后端服务调用

Passwordless Email OTP

无密码邮箱OTP

Send one-time passwords via email for passwordless login.
通过邮箱发送一次性验证码实现无密码登录。

Flow Overview

流程概述

  1. Call
    /oauth2/passwordless/login
    with callback URI
  2. SLAS POSTs
    pwdless_login_token
    to your callback
  3. Your app sends OTP to shopper via email
  4. Shopper enters OTP, app exchanges for tokens
  1. 携带回调URI调用
    /oauth2/passwordless/login
  2. SLAS 向你的回调地址POST
    pwdless_login_token
  3. 你的应用向购物者邮箱发送OTP
  4. 购物者输入OTP,应用将其兑换为令牌

Step 1: Initiate Passwordless Login

步骤1:启动无密码登录

javascript
// POST /shopper/auth/v1/organizations/{org}/oauth2/passwordless/login
async function initiatePasswordlessLogin(email, siteId) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/passwordless/login`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                user_id: email,
                mode: 'callback',
                channel_id: siteId,
                callback_uri: 'https://yoursite.com/api/passwordless/callback'
            })
        }
    );

    // SLAS will POST to your callback_uri with pwdless_login_token
    return response.json();
}
javascript
// POST /shopper/auth/v1/organizations/{org}/oauth2/passwordless/login
async function initiatePasswordlessLogin(email, siteId) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/passwordless/login`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                user_id: email,
                mode: 'callback',
                channel_id: siteId,
                callback_uri: 'https://yoursite.com/api/passwordless/callback'
            })
        }
    );

    // SLAS will POST to your callback_uri with pwdless_login_token
    return response.json();
}

Step 2: Handle Callback and Send OTP

步骤2:处理回调并发送OTP

Your callback endpoint receives
pwdless_login_token
. Generate an OTP and send it to the user:
javascript
// Your callback endpoint (receives POST from SLAS)
app.post('/api/passwordless/callback', async (req, res) => {
    const { pwdless_login_token, user_id } = req.body;

    // Generate 6-digit OTP
    const otp = Math.floor(100000 + Math.random() * 900000).toString();

    // Store token + OTP mapping (e.g., Redis with 10 min TTL)
    await redis.setex(`pwdless:${otp}`, 600, JSON.stringify({
        token: pwdless_login_token,
        email: user_id
    }));

    // Send OTP via email (configure in SLAS Admin UI)
    await sendOTPEmail(user_id, otp);

    res.status(200).send('OK');
});
你的回调端点会收到
pwdless_login_token
。生成OTP并发送给用户:
javascript
// Your callback endpoint (receives POST from SLAS)
app.post('/api/passwordless/callback', async (req, res) => {
    const { pwdless_login_token, user_id } = req.body;

    // Generate 6-digit OTP
    const otp = Math.floor(100000 + Math.random() * 900000).toString();

    // Store token + OTP mapping (e.g., Redis with 10 min TTL)
    await redis.setex(`pwdless:${otp}`, 600, JSON.stringify({
        token: pwdless_login_token,
        email: user_id
    }));

    // Send OTP via email (configure in SLAS Admin UI)
    await sendOTPEmail(user_id, otp);

    res.status(200).send('OK');
});

Step 3: Exchange OTP for Tokens

步骤3:用OTP兑换令牌

javascript
// POST /shopper/auth/v1/organizations/{org}/oauth2/passwordless/token
async function exchangeOTPForToken(otp, clientId, clientSecret, siteId) {
    // Retrieve stored token
    const stored = JSON.parse(await redis.get(`pwdless:${otp}`));
    if (!stored) throw new Error('Invalid or expired OTP');

    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/passwordless/token`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Basic ${btoa(clientId + ':' + clientSecret)}`
            },
            body: new URLSearchParams({
                grant_type: 'client_credentials',
                hint: 'pwdless_login',
                pwdless_login_token: stored.token,
                channel_id: siteId
            })
        }
    );

    // Returns: { access_token, refresh_token, ... }
    return response.json();
}
javascript
// POST /shopper/auth/v1/organizations/{org}/oauth2/passwordless/token
async function exchangeOTPForToken(otp, clientId, clientSecret, siteId) {
    // Retrieve stored token
    const stored = JSON.parse(await redis.get(`pwdless:${otp}`));
    if (!stored) throw new Error('Invalid or expired OTP');

    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/passwordless/token`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Basic ${btoa(clientId + ':' + clientSecret)}`
            },
            body: new URLSearchParams({
                grant_type: 'client_credentials',
                hint: 'pwdless_login',
                pwdless_login_token: stored.token,
                channel_id: siteId
            })
        }
    );

    // Returns: { access_token, refresh_token, ... }
    return response.json();
}

Rate Limits

速率限制

  • 6 requests per user per 10 minutes
  • 1,000 requests/month per endpoint on non-production tenants
  • 每个用户每10分钟最多6次请求
  • 非生产租户每个端点每月最多1000次请求

Passwordless SMS OTP

无密码短信OTP

Send OTP via SMS using Marketing Cloud or custom integration.
通过Marketing Cloud或自定义集成发送短信OTP。

Using Marketing Cloud

使用Marketing Cloud

Configure SMS through Salesforce Marketing Cloud:
  1. Set up Marketing Cloud connector
  2. Configure SMS journey with OTP template
  3. Trigger via SLAS callback (same flow as email OTP)
通过Salesforce Marketing Cloud配置短信:
  1. 设置Marketing Cloud连接器
  2. 配置带OTP模板的短信旅程
  3. 通过SLAS回调触发(与邮箱OTP流程一致)

Custom SMS Provider

自定义短信服务商

Use the same callback flow as email, but send via SMS provider:
javascript
// In your callback handler
const twilio = require('twilio')(accountSid, authToken);

async function sendOTPSMS(phoneNumber, otp) {
    await twilio.messages.create({
        body: `Your login code is: ${otp}`,
        from: '+1234567890',
        to: phoneNumber
    });
}
使用与邮箱OTP相同的回调流程,但通过短信服务商发送:
javascript
// In your callback handler
const twilio = require('twilio')(accountSid, authToken);

async function sendOTPSMS(phoneNumber, otp) {
    await twilio.messages.create({
        body: `Your login code is: ${otp}`,
        from: '+1234567890',
        to: phoneNumber
    });
}

Passkeys (FIDO2/WebAuthn)

通行密钥(FIDO2/WebAuthn)

Enable biometric authentication using passkeys.
Important: Passkey registration requires prior identity verification via OTP. Users must first verify their email before registering a passkey.
使用通行密钥启用生物识别认证。
注意: 通行密钥注册需要先通过OTP验证身份。用户必须先验证邮箱,才能注册通行密钥。

Registration Flow (3 Steps)

注册流程(3步)

javascript
// Step 1: Verify identity via OTP first
// Use the Email OTP flow above to verify the user

// Step 2: Start passkey registration (requires valid access token)
async function startPasskeyRegistration(accessToken) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/webauthn/register/start`,
        {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${accessToken}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                channel_id: siteId
            })
        }
    );
    return response.json();
}

// Step 3: Create credential using WebAuthn API
async function createPasskey(options) {
    const credential = await navigator.credentials.create({
        publicKey: {
            challenge: base64ToBuffer(options.challenge),
            rp: { name: options.rp_name, id: options.rp_id },
            user: {
                id: base64ToBuffer(options.user_id),
                name: options.user_name,
                displayName: options.user_display_name
            },
            pubKeyCredParams: options.pub_key_cred_params,
            authenticatorSelection: {
                authenticatorAttachment: 'platform',
                userVerification: 'required'
            }
        }
    });
    return credential;
}

// Step 4: Complete registration with SLAS
async function finishPasskeyRegistration(accessToken, credential) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/webauthn/register/finish`,
        {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${accessToken}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                channel_id: siteId,
                credential_id: bufferToBase64(credential.rawId),
                client_data_json: bufferToBase64(credential.response.clientDataJSON),
                attestation_object: bufferToBase64(credential.response.attestationObject)
            })
        }
    );
    return response.json();
}
javascript
// Step 1: Verify identity via OTP first
// Use the Email OTP flow above to verify the user

// Step 2: Start passkey registration (requires valid access token)
async function startPasskeyRegistration(accessToken) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/webauthn/register/start`,
        {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${accessToken}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                channel_id: siteId
            })
        }
    );
    return response.json();
}

// Step 3: Create credential using WebAuthn API
async function createPasskey(options) {
    const credential = await navigator.credentials.create({
        publicKey: {
            challenge: base64ToBuffer(options.challenge),
            rp: { name: options.rp_name, id: options.rp_id },
            user: {
                id: base64ToBuffer(options.user_id),
                name: options.user_name,
                displayName: options.user_display_name
            },
            pubKeyCredParams: options.pub_key_cred_params,
            authenticatorSelection: {
                authenticatorAttachment: 'platform',
                userVerification: 'required'
            }
        }
    });
    return credential;
}

// Step 4: Complete registration with SLAS
async function finishPasskeyRegistration(accessToken, credential) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/webauthn/register/finish`,
        {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${accessToken}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                channel_id: siteId,
                credential_id: bufferToBase64(credential.rawId),
                client_data_json: bufferToBase64(credential.response.clientDataJSON),
                attestation_object: bufferToBase64(credential.response.attestationObject)
            })
        }
    );
    return response.json();
}

Authentication Flow

认证流程

javascript
// Step 1: Get authentication options
async function startPasskeyAuth() {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/webauthn/authenticate/start`,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ channel_id: siteId })
        }
    );
    return response.json();
}

// Step 2: Get credential using WebAuthn API
async function authenticateWithPasskey(options) {
    const assertion = await navigator.credentials.get({
        publicKey: {
            challenge: base64ToBuffer(options.challenge),
            rpId: options.rp_id,
            allowCredentials: options.allow_credentials.map(c => ({
                type: 'public-key',
                id: base64ToBuffer(c.id)
            })),
            userVerification: 'required'
        }
    });
    return assertion;
}

// Step 3: Complete authentication and get tokens
async function finishPasskeyAuth(assertion) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/webauthn/authenticate/finish`,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                credential_id: bufferToBase64(assertion.rawId),
                client_data_json: bufferToBase64(assertion.response.clientDataJSON),
                authenticator_data: bufferToBase64(assertion.response.authenticatorData),
                signature: bufferToBase64(assertion.response.signature),
                channel_id: siteId
            })
        }
    );
    return response.json();
}
javascript
// Step 1: Get authentication options
async function startPasskeyAuth() {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/webauthn/authenticate/start`,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ channel_id: siteId })
        }
    );
    return response.json();
}

// Step 2: Get credential using WebAuthn API
async function authenticateWithPasskey(options) {
    const assertion = await navigator.credentials.get({
        publicKey: {
            challenge: base64ToBuffer(options.challenge),
            rpId: options.rp_id,
            allowCredentials: options.allow_credentials.map(c => ({
                type: 'public-key',
                id: base64ToBuffer(c.id)
            })),
            userVerification: 'required'
        }
    });
    return assertion;
}

// Step 3: Complete authentication and get tokens
async function finishPasskeyAuth(assertion) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/webauthn/authenticate/finish`,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                credential_id: bufferToBase64(assertion.rawId),
                client_data_json: bufferToBase64(assertion.response.clientDataJSON),
                authenticator_data: bufferToBase64(assertion.response.authenticatorData),
                signature: bufferToBase64(assertion.response.signature),
                channel_id: siteId
            })
        }
    );
    return response.json();
}

Session Bridge

会话桥接

Maintain session continuity between PWA Kit and SFRA storefronts.
在PWA Kit与SFRA店面之间保持会话连续性。

Token Types

令牌类型

Session bridge uses signed tokens generated from SFRA script APIs:
  • dwsgst
    - Guest session token (from
    Session.generateGuestSessionSignature()
    )
  • dwsrst
    - Registered session token (from
    Session.generateRegisteredSessionSignature()
    )
Note: DWSID is deprecated for registered shoppers.
会话桥接使用由SFRA脚本API生成的签名令牌:
  • dwsgst
    - 访客会话令牌(来自
    Session.generateGuestSessionSignature()
  • dwsrst
    - 注册用户会话令牌(来自
    Session.generateRegisteredSessionSignature()
注意: DWSID已不再用于注册用户。

PWA to SFRA Bridge

PWA 到 SFRA 桥接

javascript
// In PWA Kit: Get session bridge tokens
async function getSessionBridgeTokens(accessToken) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/session-bridge/token`,
        {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${accessToken}`,
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                channel_id: siteId,
                login_id: customerId
            })
        }
    );

    // Returns: { dwsgst, dwsrst }
    return response.json();
}

// Redirect to SFRA with tokens
function redirectToSFRA(dwsgst, dwsrst) {
    const sfraUrl = new URL('https://sfra.yoursite.com/');
    sfraUrl.searchParams.set('dwsgst', dwsgst);
    if (dwsrst) {
        sfraUrl.searchParams.set('dwsrst', dwsrst);
    }
    window.location.href = sfraUrl.toString();
}
javascript
// In PWA Kit: Get session bridge tokens
async function getSessionBridgeTokens(accessToken) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/session-bridge/token`,
        {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${accessToken}`,
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                channel_id: siteId,
                login_id: customerId
            })
        }
    );

    // Returns: { dwsgst, dwsrst }
    return response.json();
}

// Redirect to SFRA with tokens
function redirectToSFRA(dwsgst, dwsrst) {
    const sfraUrl = new URL('https://sfra.yoursite.com/');
    sfraUrl.searchParams.set('dwsgst', dwsgst);
    if (dwsrst) {
        sfraUrl.searchParams.set('dwsrst', dwsrst);
    }
    window.location.href = sfraUrl.toString();
}

SFRA to PWA Bridge

SFRA 到 PWA 桥接

javascript
// In SFRA controller: Generate bridge tokens
var Session = require('dw/system/Session');

function bridgeToPWA() {
    var dwsgst = Session.generateGuestSessionSignature();
    var dwsrst = customer.authenticated ?
        Session.generateRegisteredSessionSignature() : null;

    response.redirect(
        'https://pwa.yoursite.com/callback' +
        '?dwsgst=' + dwsgst +
        (dwsrst ? '&dwsrst=' + dwsrst : '')
    );
}
javascript
// In SFRA controller: Generate bridge tokens
var Session = require('dw/system/Session');

function bridgeToPWA() {
    var dwsgst = Session.generateGuestSessionSignature();
    var dwsrst = customer.authenticated ?
        Session.generateRegisteredSessionSignature() : null;

    response.redirect(
        'https://pwa.yoursite.com/callback' +
        '?dwsgst=' + dwsgst +
        (dwsrst ? '&dwsrst=' + dwsrst : '')
    );
}

PWA Kit Callback Handler

PWA Kit 回调处理器

javascript
// In PWA Kit: Handle bridge callback
async function handleBridgeCallback(searchParams) {
    const dwsgst = searchParams.get('dwsgst');
    const dwsrst = searchParams.get('dwsrst');

    // Exchange bridge tokens for access token
    // Use hint=sb-guest for guest, hint=sb-user for registered
    const hint = dwsrst ? 'sb-user' : 'sb-guest';

    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/session-bridge/token`,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                grant_type: 'session_bridge',
                hint: hint,
                channel_id: siteId,
                dwsgst: dwsgst,
                ...(dwsrst && { dwsrst: dwsrst })
            })
        }
    );

    const tokens = await response.json();
    // Store tokens and establish session
}
javascript
// In PWA Kit: Handle bridge callback
async function handleBridgeCallback(searchParams) {
    const dwsgst = searchParams.get('dwsgst');
    const dwsrst = searchParams.get('dwsrst');

    // Exchange bridge tokens for access token
    // Use hint=sb-guest for guest, hint=sb-user for registered
    const hint = dwsrst ? 'sb-user' : 'sb-guest';

    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/session-bridge/token`,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                grant_type: 'session_bridge',
                hint: hint,
                channel_id: siteId,
                dwsgst: dwsgst,
                ...(dwsrst && { dwsrst: dwsrst })
            })
        }
    );

    const tokens = await response.json();
    // Store tokens and establish session
}

Hybrid Authentication (B2C 25.3+)

混合认证(B2C 25.3+)

Hybrid Auth replaces Plugin SLAS for hybrid PWA/SFRA storefronts. It's built directly into the B2C platform and provides automatic session synchronization.
混合认证替代了Plugin SLAS,适用于混合PWA/SFRA店面。它直接内置于B2C平台,提供自动会话同步功能。

Benefits

优势

  • No manual session bridge implementation needed
  • Automatic sync between PWA and SFRA
  • Simplified token management
  • Built-in platform support
  • 无需手动实现会话桥接
  • PWA与SFRA之间自动同步
  • 简化令牌管理
  • 平台内置支持

Migration from Plugin SLAS

从Plugin SLAS迁移

If using Plugin SLAS, migrate to Hybrid Auth:
  1. Upgrade to B2C Commerce 25.3+
  2. Enable Hybrid Auth in Business Manager
  3. Remove Plugin SLAS cartridge
  4. Update storefront to use platform auth
如果你正在使用Plugin SLAS,可按以下步骤迁移到混合认证:
  1. 升级到B2C Commerce 25.3+版本
  2. 在Business Manager中启用混合认证
  3. 移除Plugin SLAS cartridge
  4. 更新店面以使用平台认证

Token Refresh

令牌刷新

Important: The
channel_id
parameter is required for guest token refresh.
重要提示: 访客令牌刷新必须携带
channel_id
参数。

Public Clients (Single-Use Refresh)

公开客户端(单次使用刷新令牌)

Public clients (no secret) receive single-use refresh tokens:
javascript
async function refreshTokenPublic(refreshToken, clientId, siteId) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/token`,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                grant_type: 'refresh_token',
                refresh_token: refreshToken,
                client_id: clientId,
                channel_id: siteId  // REQUIRED
            })
        }
    );

    // Returns NEW refresh_token (old one is invalidated)
    return response.json();
}
公开客户端(无密钥)会收到单次使用的刷新令牌:
javascript
async function refreshTokenPublic(refreshToken, clientId, siteId) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/token`,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                grant_type: 'refresh_token',
                refresh_token: refreshToken,
                client_id: clientId,
                channel_id: siteId  // REQUIRED
            })
        }
    );

    // Returns NEW refresh_token (old one is invalidated)
    return response.json();
}

Private Clients (Reusable Refresh)

私有客户端(可重复使用刷新令牌)

Private clients can reuse refresh tokens:
javascript
async function refreshTokenPrivate(refreshToken, clientId, clientSecret, siteId) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/token`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Basic ${btoa(clientId + ':' + clientSecret)}`
            },
            body: new URLSearchParams({
                grant_type: 'refresh_token',
                refresh_token: refreshToken,
                channel_id: siteId  // REQUIRED
            })
        }
    );

    // Same refresh_token can be used again
    return response.json();
}
私有客户端可重复使用刷新令牌:
javascript
async function refreshTokenPrivate(refreshToken, clientId, clientSecret, siteId) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/token`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Basic ${btoa(clientId + ':' + clientSecret)}`
            },
            body: new URLSearchParams({
                grant_type: 'refresh_token',
                refresh_token: refreshToken,
                channel_id: siteId  // REQUIRED
            })
        }
    );

    // Same refresh_token can be used again
    return response.json();
}

Trusted System on Behalf (TSOB)

可信系统代操作(TSOB)

Server-to-server authentication to act on behalf of a shopper.
服务器到服务器的认证,代表购物者执行操作。

Use Cases

使用场景

  • Backend services accessing shopper data
  • Order management systems
  • Customer service applications
  • 后端服务访问购物者数据
  • 订单管理系统
  • 客户服务应用

Get Token on Behalf of Shopper

获取代表购物者的令牌

javascript
async function getTSOBToken(shopperLoginId) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/trusted-system/token`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Basic ${btoa(clientId + ':' + clientSecret)}`
            },
            body: new URLSearchParams({
                grant_type: 'client_credentials',
                login_id: shopperLoginId,
                channel_id: siteId,
                usid: shopperUsid // Optional: reuse existing session
            })
        }
    );

    // Returns tokens that act as the specified shopper
    return response.json();
}
javascript
async function getTSOBToken(shopperLoginId) {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/trusted-system/token`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Basic ${btoa(clientId + ':' + clientSecret)}`
            },
            body: new URLSearchParams({
                grant_type: 'client_credentials',
                login_id: shopperLoginId,
                channel_id: siteId,
                usid: shopperUsid // Optional: reuse existing session
            })
        }
    );

    // Returns tokens that act as the specified shopper
    return response.json();
}

Important Constraints

重要限制

3-Second Protection Window: Multiple TSOB calls for the same shopper within 3 seconds return HTTP 409:
"Tenant id <id> has already performed a login operation for user id <user_id> in the last 3 seconds."
Handle this in your code:
javascript
async function getTSOBTokenWithRetry(shopperLoginId, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            return await getTSOBToken(shopperLoginId);
        } catch (error) {
            if (error.status === 409 && i < maxRetries - 1) {
                await new Promise(r => setTimeout(r, 3000));
                continue;
            }
            throw error;
        }
    }
}
3秒保护窗口: 同一购物者在3秒内多次调用TSOB会返回HTTP 409错误:
"Tenant id <id> has already performed a login operation for user id <user_id> in the last 3 seconds."
在代码中处理该情况:
javascript
async function getTSOBTokenWithRetry(shopperLoginId, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            return await getTSOBToken(shopperLoginId);
        } catch (error) {
            if (error.status === 409 && i < maxRetries - 1) {
                await new Promise(r => setTimeout(r, 3000));
                continue;
            }
            throw error;
        }
    }
}

Required Configuration

必要配置

  1. SLAS client must have TSOB enabled (
    sfcc.ts_ext_on_behalf_of
    scope)
  2. Configure in SLAS Admin API or Business Manager
  3. Secure the client secret (server-side only)
  4. Keep
    login_id
    length under 60 characters
  1. SLAS客户端必须启用TSOB(
    sfcc.ts_ext_on_behalf_of
    权限)
  2. 在SLAS Admin API或Business Manager中配置
  3. 安全存储客户端密钥(仅在服务器端使用)
  4. login_id
    长度不超过60个字符

JWT Validation

JWT验证

Validate SLAS tokens using JWKS (JSON Web Key Set).
使用JWKS(JSON Web Key Set)验证SLAS令牌。

Get JWKS

获取JWKS

javascript
async function getJWKS() {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/jwks`
    );
    return response.json();
}
javascript
async function getJWKS() {
    const response = await fetch(
        `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/jwks`
    );
    return response.json();
}

Validate Token

验证令牌

javascript
const jose = require('jose');

async function validateToken(accessToken) {
    // Get JWKS
    const jwksUrl = `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/jwks`;
    const JWKS = jose.createRemoteJWKSet(new URL(jwksUrl));

    // Verify token
    const { payload } = await jose.jwtVerify(accessToken, JWKS, {
        issuer: `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}`,
        audience: clientId
    });

    return payload;
}
javascript
const jose = require('jose');

async function validateToken(accessToken) {
    // Get JWKS
    const jwksUrl = `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}/oauth2/jwks`;
    const JWKS = jose.createRemoteJWKSet(new URL(jwksUrl));

    // Verify token
    const { payload } = await jose.jwtVerify(accessToken, JWKS, {
        issuer: `https://${shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/${orgId}`,
        audience: clientId
    });

    return payload;
}

Token Claims

令牌声明

ClaimDescription
sub
Subject (customer ID or guest ID)
isb
Identity subject binding
iss
Issuer
aud
Audience (client ID)
exp
Expiration time
iat
Issued at time
scope
Granted scopes
tsob
TSOB token type (for trusted system tokens)
声明描述
sub
主体(客户ID或访客ID)
isb
身份主体绑定
iss
签发者
aud
受众(客户端ID)
exp
过期时间
iat
签发时间
scope
授予的权限
tsob
TSOB令牌类型(针对可信系统令牌)

Best Practices

最佳实践

Security

安全

  • Never expose client secrets in frontend code
  • Use HTTPS for all token exchanges
  • Validate tokens server-side for sensitive operations
  • Implement proper CORS policies
  • Store tokens securely (httpOnly cookies preferred)
  • 切勿在前端代码中暴露客户端密钥
  • 所有令牌交换均使用HTTPS
  • 敏感操作必须在服务器端验证令牌
  • 实现合适的CORS策略
  • 安全存储令牌(优先使用httpOnly Cookie)

Token Management

令牌管理

  • Implement proactive token refresh before expiry
  • Handle refresh token rotation for public clients
  • Clear tokens on logout from all storage locations
  • Use short-lived access tokens where possible
  • Always include
    channel_id
    in refresh requests
  • 在令牌过期前主动执行刷新
  • 为公开客户端处理刷新令牌轮换
  • 登出时从所有存储位置清除令牌
  • 尽可能使用短有效期的访问令牌
  • 刷新请求中始终包含
    channel_id
    参数

User Experience

用户体验

  • Provide fallback authentication methods
  • Show clear error messages for auth failures
  • Remember user's preferred auth method
  • Handle session expiry gracefully
  • 提供备选认证方式
  • 认证失败时显示清晰的错误信息
  • 记住用户偏好的认证方式
  • 优雅处理会话过期

Detailed References

详细参考

  • Session Bridge Flows - Detailed session bridge implementation
  • Token Lifecycle - Token expiry and refresh patterns
  • 会话桥接流程 - 会话桥接的详细实现
  • 令牌生命周期 - 令牌过期与刷新模式