apollo icon indicating copy to clipboard operation
apollo copied to clipboard

How to use dynamic Bearer token [Help]

Open DidoMarchet opened this issue 3 years ago • 1 comments

Hi guys, I cannot figure out how to use a Bearer code obtained after a login.

I've got this situation in asyncData:

const token = await myTokenFn() //  A function that return a token

const data = await this.$apollo.query({
    query,
    variables,
    // I NEED TO PASS AND USE MY TOKEN
})

Any advices or example is appreciated!

Thanks in advance and kind regards,

Davide

DidoMarchet avatar Nov 29 '21 10:11 DidoMarchet

Were you able to workaround with this?

MuhaddiMu avatar Dec 11 '21 11:12 MuhaddiMu

I'm also looking for a way to use bearer token.

hermesalvesbr avatar Mar 07 '23 11:03 hermesalvesbr

Hi, I do that: in the apollo configuration file I added the configuration of the client:

export default {
  apollo: {
    clientConfigs: {
      saleor: '~/configuration/apollo/config-saleor.js',
    },
    errorHandler: '~/configuration/apollo/error-handler.js',
  },
}

and in the configuration file of my client (config-saleor.js) I do:

export default ({ store, app }) => {
  return {
    httpEndpoint: process.env.NUXT_ENV_SALEOR_GQL_URL,
    getAuth: () => {
      return store.state.saleor.user.user &&
        store.state.localStorage?.auth?.token &&
        !app.$useSaleor.fetch.tokenNeedRefresh()
        ? `Bearer ${store.state.localStorage?.auth?.token}`
        : ''
    },
  }
}

so I check if the token is valid (this is my own check but you can use yours).

I refresh the token during the navigation using a router middleware. Note: I use my own chekc and function in the if state and in the dispatch do you can use your owns.

export default async function ({ store, app }) {
  if (app.$useSaleor.fetch.tokenNeedRefresh()) {
    await store.dispatch('saleor/user/updateUser', {
      key: 'refreshToken',
      dataForm: {
        refreshToken: store.state.localStorage?.auth?.refreshToken,
      },
    })
    store.dispatch('localStorage/setAuth')
  }
}

Thanks and kind regards,

Davide

DidoMarchet avatar Mar 07 '23 11:03 DidoMarchet