obabichev / react-token-auth

84 stars 22 forks source link

Error: Access token can not be extracted. Either whole 'session' must be a string (access token only) or 'getAccessToken' function should be provided #30

Open RylanSchaeffer opened 2 years ago

RylanSchaeffer commented 2 years ago

Hi! I'm a novice to React and JS, and I'm trying to get around the following error: Uncaught (in promise) Error: Access token can not be extracted. Either whole 'session' must be a string (access token only) or 'getAccessToken' function should be provided.

My error occurs in the following code:

const handleSubmit = (e) => {

  e.preventDefault();

  let opts = {
    "price_id": "price_1LAHFfANX7SRTyI1CAVCDmNl",
    // TODO: Add auth token
  }

  authFetch(
    // fetch(
    `${process.env.REACT_APP_URL_BACKEND}/create-checkout-session`,
    {
      method: 'post',
      body: JSON.stringify(opts)
    })
  .then(r => {
    console.log(r.json())
    return r.json()})
  // .then(token => {
  //   if (token.access_token){
  //     // Saves token to local storage.
  //     login(token)
  //     console.log(token)
  //   }
  //   else {
  //     // TODO: Display message if invalid credentials are provided.
  //     console.log("Invalid credentials.")
  //   }
  //   console.log(token)
  // })
}

Can someone explain to me why this occurs and how to fix it?

RylanSchaeffer commented 2 years ago

This is the problematic code:

exports.extractAccessToken = function (session, getAccessToken) {
    if (!session) {
        return null;
    }
    if (getAccessToken) {
        return getAccessToken(session);
    }
    if (typeof session !== 'string') {
        throw Error("Access token can not be extracted. Either whole 'session' must be a string (access token only) or 'getAccessToken' function should be provided");
    }
    return session;
};

My session is:

Object { access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NTUyNDkwMjYsImV4cCI6MTY1NTMzNTQyNiwianRpIjoiODkzYzUwZTItMjkwOC00MDMxLWJhMGQtOWMzZWIxMzdlMDNkIiwiaWQiOjUsInJscyI6ImV4cGxvcmVyIiwicmZfZXhwIjoxNjU3ODQxMDI2fQ.wEJE9qZZZdwHuWnIm2y5XblkNiWeMmD1zmaIfkijlic" }

but getAccessToken is undefined, so the error is thrown.

RylanSchaeffer commented 2 years ago

I just checked the following: If I use

let [isSignedIn, session] = useAuth();

session is indeed:

Object { access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NTUyNDkwMjYsImV4cCI6MTY1NTMzNTQyNiwianRpIjoiODkzYzUwZTItMjkwOC00MDMxLWJhMGQtOWMzZWIxMzdlMDNkIiwiaWQiOjUsInJscyI6ImV4cGxvcmVyIiwicmZfZXhwIjoxNjU3ODQxMDI2fQ.wEJE9qZZZdwHuWnIm2y5XblkNiWeMmD1zmaIfkijlic" }
RylanSchaeffer commented 2 years ago

The problem seems to be that this line leaves getAccessToken undefined:

var _c = _a.storageKey, storageKey = _c === void 0 ? 'REACT_TOKEN_AUTH_KEY' : _c, onUpdateToken = _a.onUpdateToken, onHydratation = _a.onHydratation, _d = _a.storage, storage = _d === void 0 ? defaultStore_1.createDefaultStore((_b = {}, _b[storageKey] = localStorage.getItem(storageKey), _b)) : _d, _e = _a.fetchFunction, fetchFunction = _e === void 0 ? fetch : _e, getAccessToken = _a.getAccessToken, _f = _a.expirationThresholdMillisec, expirationThresholdMillisec = _f === void 0 ? 5000 : _f;
RylanSchaeffer commented 2 years ago

This is my current workaround:

  fetch(
    `${process.env.REACT_APP_URL_BACKEND}/create-checkout-session`,
    {
      method: 'post',
      headers: {
        'Authorization': `Bearer ${session.access_token}`
      },
      body: JSON.stringify(opts),
    }
    )
  .then(r => r.json())
  .then(response => {
    console.log(response)
  })
medonni commented 2 years ago

This is my current workaround:

  fetch(
    `${process.env.REACT_APP_URL_BACKEND}/create-checkout-session`,
    {
      method: 'post',
      headers: {
        'Authorization': `Bearer ${session.access_token}`
      },
      body: JSON.stringify(opts),
    }
    )
  .then(r => r.json())
  .then(response => {
    console.log(response)
  })

When i attempt this workaround i'm getting Uncaught TypeError: Cannot read properties of null (reading 'access_token'). Have you had that happen before?