zablik
zablik

Reputation: 53

Using vuex-oidc how and where to set `access_token` in axios default headers and keep it in current state

In order to access an API a need to add the current JWT token to API client's default headers. oidcStore module has an API to get access_token, it is oidcAccessToken getter.

So my question is how can I call this oidcAccessToken getter inside userLoaded event callback? Maybe there is a better place to set this header? Is there an event to handle access_token change?

Thanks!

// In my `store/index.js`

export default createStore({
  state: {},
  mutations: {},
  actions: {},
  modules: {
    oidcStore: vuexOidcCreateStoreModule(
      oidcSettings,
      {
        namespaced: true
      },
      {
        userLoaded(user) {
           // set access_token
          axios.defaults.headers.common['Auth-Token'] = ... ;
        },
        userUnloaded() {
           // delete access_token
           axios.defaults.headers.common['Auth-Token'] = null;
        }
      }
    )
  }
});

Upvotes: 1

Views: 1568

Answers (2)

harsh chaudhary
harsh chaudhary

Reputation: 11

You can use axios interceptors.

With interceptors, You can intercept requests or responses before they are handled by then or catch. Check documentation: https://axios-http.com/docs/interceptors

I have implemented it in the following way: In main.js file

import axios from 'axios';
import store from './store';

axios.interceptors.request.use((request) => {
    if (store.state.oidcStore.access_token) {
      request.headers.Authorization = `Bearer ${store.state.oidcStore.access_token}`;
    }
});

You can replace Authorization with ['Auth-Token'] for your code.

Note:

  • Axios interceptor read the state before every axios network call and add Auth header to the request.

  • By default, the value of access_token is null. With this solution, you do not have to look for the event and manage a different state variable. Just read the value from oidcStore state. It is managed by the library itself.

    Here are the default values of oidcStore state variables in Vue Devtool.

Upvotes: 1

zablik
zablik

Reputation: 53

According to the reply of the creator of a library https://github.com/perarnborg/vuex-oidc/issues/153

the good way to do this is simply use

        userLoaded(user) {
           // set access_token
          axios.defaults.headers.common['Auth-Token'] = `Bearer ${user.access_token}`;
        },

Upvotes: 1

Related Questions