How can i pass the jwt token to axios get request?



  • I wanted to pass the jwt token to the axios get request,here is my store file where i wrote action to set the token using localstorage :

    const actions = {
      tokenlogin({}, payload) 
    	{
    		console.log('*auth_login*')
    		console.log('payload:', payload)
    		axios.post('http://127.0.0.1:8000/api/token', payload)
    		.then((response) => {
    				console.log(response.data);
    				console.log(response.data.access)
                     
        if(response.data.access)
        {
            localStorage.setItem('token', response.data.access)
            this.$router.push({path: '/dashboard'})
        }
          else
          {
            console.log('**** else part ***')
            this.show=true;
            // this.alert1 = true;
    
          }
            },
              error => {
                console.log('********* error *********');
                console.log(error)
            });
          },
    }
    

    And this is the page where i got that tokeand i have to pass this token to the axios get request :

    data(){
            var token1=localStorage.getItem('token')
            console.log(token1)
           
            if ( token1 == null )
            { 
                this.$router.push({path: '/'})
            }
            else
            {
                var page = 1;
                
                var baseurl='http://127.0.0.1:8000/api/'
                this.$axios.get(baseurl+'hospitalget/?page='+page)
                   .then((response) => {
                   console.log(response)
                    page++;
                    console.log(page)
                   for(var i=0; i<response.data.results.length;i++)
                   {
                      this.hospital_data.push({id:response.data.results[i].hospital_id,name:response.data.results[i].hospital_name,address:response.data.results[i].hospital_address});
                   }
                   console.log(this.hospital_data)
                      
                   })
            }
    
    
            return{
               token1,
               data:[],
               username:'',
               hospital_data:[],
               id:'',
               name:'',
               address:'',
               hospital_name:'',
               showEditTask: false,
               page:1,
             }
        },
    
    

    How can i append the jwt token to request?





  • In latest version of quasar, main.js file is not there.Where i have set the axios headers.







  • I tried few stuff in an old project, maybe there are many things to improve, anyway I think it is interesting.

    I store my token and get it with a login method
    store/user/actions.js

    import { axiosInstance } from 'boot/axios'
    import JWT from 'jwt-client'
    
    export function login ({ commit }, form) {
      console.log('action login')
      return axiosInstance.post('/login', { email: form.email, password: form.password })
        .then(response => {
          console.log('success login')
          let session = JWT.read(response.data.token)
          // console.log(response.data, session.claim.auth)
          commit('login', { token: response.data.token, refeshToken: response.data.refesh_token, user: response.data.user, authorization: session.claim.auth })
          setAxiosHeaders(response.data.token)
          return true
        })
        .catch((error) => {
          console.log('error login')
          // console.log(error.response.data)
          console.log(error)
          return false
        })
    }
    

    catch error to refresh token, maybe not the right way to do a refresh but the point is the concept
    boot/axios.js

    import axios from 'axios'
    import { refreshToken } from '../store/user/getters';
    
    const axiosInstance = axios.create({
      baseURL: 'https://0.0.0.0:5000'
       })
    })
    
    axiosInstance.interceptors.response.use((response) => { // intercept the global error
      return response
    }, function (error) {
      let originalRequest = error.config
      if (error.response.status === 401 && !originalRequest._retry) { // if the error is 401 and hasent already been retried
        originalRequest._retry = true // now it can be retried 
        return axiosInstance.post('/users/token', null).then((data) => {
          return axiosInstance(originalRequest) // retry the request that errored out
        }).catch((error) => {
          for (let i = 0; i < error.response.data.errors.length; i++) {
            if (error.response.data.errors[i] === 'TOKEN-EXPIRED') {
              // refesh the token and try again
              refresh()
              return
            }
          }
        })
      }
      if (error.response.status === 404 && !originalRequest._retry) {
        originalRequest._retry = true
        window.location.href = '/'
        return
      }
      // Do something with response error
      return Promise.reject(error)
    })
    
    export default ({ Vue }) => {
      // for use inside Vue files through this.$axios
      Vue.prototype.$axios = axiosInstance
    }
    
    // Here we define a named export
    // that we can later use inside .js files:
    export { axiosInstance }
    
    


  • This is my axios boot file:

    export default ({ router, store, Vue }) => {
      const baseURL = getbaseURL()
      const instance = axios.create({
        baseURL: baseURL
      })
      store.commit('http/axios', instance)
      store.commit('http/baseUrl', baseURL)
      Vue.prototype.$axios = instance
    
      instance.interceptors.response.use(function (response) {
        return response
      }, function (error) {
        if (error.response && error.response.status === 401) {
          // not authorized, redirect to login page
          router.app.$root.$emit('auth:token-expired')
        }
        return Promise.reject(error)
      })
    }
    

    Then, I also keep track with Vuex. This is a mutation after login:

    import JWT from 'jwt-client'
    
    export const logout = (state) => {
      // reset saved token
      state.token = null
      // remove token from local storage
      JWT.forget()
    }
    
    export const setToken = (state, { token, axios }) => {
      // all is good, validate the token
      if (JWT.validate(token)) {
        // keep token in localstorage
        JWT.keep(token)
        // update axios
        axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
        if (token) {
          axios.defaults.headers.common['X-Access-Token'] = token
        }
        else {
          axios.defaults.headers.common['X-Access-Token'] = ''
        }
        // console.log('token updated')
      }
      else {
        console.error('JWT failed to validate token')
        token = null
      }
    
      // console.log('old token:', state.token)
      state.token = token
      // console.log('new token:', state.token)
    
      return state.token
    }
    

    in router/index.js I added this function:

      function isValidLoggedIn () {
        let updatedToken = false
        let isLoggedIn = store.getters['auth/isLoggedIn']
        if (!isLoggedIn) {
          // see if there is a token in localstorage
          let token = JWT.get()
          if (token) {
            // check if expired
            if (tokenHelper.isExpired(token)) {
              console.error('Token expiredFor:', tokenHelper.expiredFor(token))
              token = null
            }
            else {
              updatedToken = true
            }
          }
          store.commit('auth/setToken', { token, axios: store.getters['http/axios'] })
          // re-get logged in status
          isLoggedIn = store.getters['auth/isLoggedIn']
    
          if (updatedToken && isLoggedIn) {
            store._vm.$emit('auth:logged-in')
          }
        }
    
        return isLoggedIn
      }
    

    then used in the router’s beforeEach:

        let allowedToEnter = true
        to.matched.some((record) => {
          // check if there is meta data
          const isLoggedIn = isValidLoggedIn()
          if (!isLoggedIn && record.name === 'home') {
            next({
              path: '/sign-in',
              replace: true
            })
            return
          }
    
          if ('meta' in record) {
            // ------------------------------------------------------------
            // check if user needs to be logged in to access this page
            if ('requiresAuth' in record.meta) {
              if (record.meta.requiresAuth) {
                // console.log('Page requires auth:', to, from)
                // this route requires auth, check if user is logged in
                // if not, redirect to login page.
                if (!isLoggedIn) {
                  // User is not logged in, redirect to signin page
                  allowedToEnter = false
                  next({
                    path: '/sign-in',
                    replace: true,
                    // redirect back to original path when done signing in
                    query: { redirect: to.fullPath }
                  })
                }
              }
            }
            // ------------------------------------------------------------
            // check if user has correct permissions to access this page
            if (allowedToEnter && 'permissions' in record.meta) {
              let canProceed = false
              const permissions = record.meta.permissions
              // get currently logged in user permissions
              const token = store.getters['auth/token']
              // decipher the token
              const session = JWT.read(token)
              // check if they are not an admin (administrator)
              if (session.claim.permissions.administrator) {
                canProceed = true
              }
              else {
                for (let index = 0; index < permissions.length; ++index) {
                  const permission = permissions[index]
                  // console.log('Permission needed:', permission)
                  if (permission === 'administrator') {
                    if (session.claim.permissions.administrator) {
                      canProceed = true
                    }
                  }
                  else if (permission === 'liveview') {
                    if (session.claim.permissions.liveview) {
                      canProceed = true
                    }
    ...
              if (!canProceed) {
                allowedToEnter = false
                // redirect to not-authorized page
                next({
                  path: '/not-authorized',
                  replace: true
                })
              }
            }
          }
        })
    
        if (allowedToEnter) {
          // go to the requested page
          next()
        }
      })
    

    Hope this helps


Log in to reply