SalesforceCommerceCloud / commerce-sdk-isomorphic

Browser & Node.js JavaScript client for B2C Commerce API
https://salesforcecommercecloud.github.io/commerce-sdk-isomorphic/
BSD 3-Clause "New" or "Revised" License
42 stars 20 forks source link

Support use with HTTP basic auth and Commerce API on the same domain #79

Closed johnboxall closed 1 year ago

johnboxall commented 2 years ago

Folks may want to use commerce-sdk-isomorphic on domains that are protected by HTTP Basic Auth.

Currently, it is not possible to do this if Commerce API is proxied under the same domain as basic auth is used as in browser, the HTTP authorization header used by Commerce API conflicts with the one used by Basic Auth.

This is a common scenario, as Commerce API doesn't support CORS and "proxying" it under the same domain is a common performance optimization and folks want to protect their in-progress storefronts from prying eyes and robots.

This issue is complex:

  1. The way browsers implement basic auth is that they store credentials associated with a domain after they encounter the basic auth headers. On subsequent requests to the same domain, the browsers automatically adds that header. Basic auth is sent via the Authorization header.
  2. SCAPI also wants to use the Authorization header.
  3. We end up with a race where both the browser and this lib try to set the Auth header and the wrong header is sent (eg. the basic auth for HTTP Auth rather than SCAPI)

Normally, you can disable this behaviour using fetch's using the credentials: "omit" option:

However, the way we're currently using cross-fetch means that the transport mechanism is XHR, which doesn't support disabling sending credentials for same-origins: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

I think the solution may involve allowing the use of native fetch in browser and then folks can choose to pass the credentials to fetchOptions.

gkhunger-sf commented 2 years ago

Hi John,

If you have a sample code for this that would be very helpful.

-Gaurav

JurajVajdaCQL commented 2 years ago

@gkhunger-sf the code example is here: https://github.com/SalesforceCommerceCloud/pwa-kit/compare/example-basic-auth exclude the changes done in packages/pwa/app/commerce-api/index.js and you will see error in /token call caused by incorrect Authorization header token from the basic auth image

the solution/workaround for this are the changes in packages/pwa/app/commerce-api/index.js but even this is not working for everybody. We have multiple users experiencing the same issue (in the screenshot above) even with the changes in packages/pwa/app/commerce-api/index.js. So that solution/workaround is not buletproof :(

johnboxall commented 1 year ago

Fixed in #116.