vuestorefront / vue-storefront-api

Vue.js storefront for Magento2 (and not only) - data backend
https://www.vuestorefront.io
MIT License
348 stars 338 forks source link

Invalid token for guest when tokenInHeader is true #547

Open rain2o opened 3 years ago

rain2o commented 3 years ago

I have started trying to use the new option for config.users.tokenInHeader to move the customer tokens out of the parameters, however I'm running into an issue. If a guest user performs an action (in my example, the create cart endpoint is called before adding a product to cart), the authorization header is sent as "Bearer ", because a guest does not have a token. This is expected.

However, it seems the extra whitespace in the value is getting stripped during the request (I'm not entirely sure at which point this happens), which means the authorization value which is received by the API is "Bearer" (no trailing whitespace).

What this means is, getToken does not remove "Bearer" because it is looking for "Bearer ", with a trailing space.

If this is a unique problem that is not reproduced by others, then I can continue to investigate what is stripping the value. However, if this is in fact normal behavior, then I wonder if it would be better to do the following:

export function getToken (req) {
  return config.users.tokenInHeader
    ? (req.headers.authorization || '').replace('Bearer', '').trim()
    : req.query.token
}

This will always remove "Bearer" and then remove any remaining trailing or leading whitespace. A quick test in my environment worked with this change.