SHOPin Logo
Skip to main documentation content

Login flow

Authentication · Login flow

It is important to read the sections Why this shape and Reference example and production readiness on Authentication before relying on this page. They explain why the default BFF-centred pattern exists, how you can extend or replace it, and what the reference implementation does and does not promise for production.

How the reference flow works: the presentation app posts credentials to the BFF; the BFF runs the OAuth 2.0 password grant through the active auth provider (for example commercetools-auth when Commercetools is your identity backend), and stores tokens in HTTP-only cookies. Cart setup after login goes through handleAuthWithCartSetup in auth.controller.ts. Shapes live in core/contracts/src/auth/login.

Login process

  1. CSRF token retrieval — The presentation app requests a CSRF token from the BFF (for example GET /csrf/token). The server generates a token, stores it in an HTTP-only cookie, and returns it in the response body.

  2. Login request — The presentation app sends POST /auth/login with:

    • Email and password in the request body
    • CSRF token in the header the BFF expects (for example X-CSRF-Token)
    • CSRF cookie (sent automatically by the browser)
  3. CSRF validation — The BFF checks that the header token matches the cookie token using constant-time comparison.

  4. Authentication — The BFF forwards credentials to the auth provider using the OAuth 2.0 password grant—for example Commercetools when that is your identity stack. The provider validates credentials and returns access and refresh tokens. The BFF may also check email verification and merge an anonymous cart if the shopper had a guest session.

  5. Token storage — On success, the BFF:

    • Encrypts and signs tokens using nested JWT (JWS + JWE)
    • Stores them in HTTP-only cookies (secure, httpOnly, SameSite)
    • Sets access token expiration from the auth provider response (for example Commercetools)
    • Sets the refresh token with a longer expiration (Tokens covers cookie bounds and REFRESH_TOKEN_MAX_AGE)
    • Sets up the cart (for example guest cart merge, customer cart)
  6. Response — The BFF returns a success or error status. The presentation app shows feedback and redirects or updates the UI.

Error handling

  • Invalid credentials — Returns 401 Unauthorized with an error message
  • Validation errors — Returns 400 Bad Request for invalid input
  • CSRF token mismatch — Returns 403 Forbidden

Security features (login)

  • CSRF protection via double-submit cookie pattern
  • Tokens stored in HTTP-only cookies (not accessible to JavaScript)
  • Tokens encrypted and signed before storage
  • Secure cookie flags (secure, httpOnly, SameSite)
  • Constant-time comparison for CSRF validation

Related

Back to Authentication · Back to How to work with SHOPin