0

I am trying to retrieve the user from my JWT token which is being served from a Django-Rest API endpoint, /get-token/ and store the user in my Vuex Store.

I don't have an endpoint set up to return the logged in user, and while this could be a potential solution I see no reason to do that instead of retrieving the user from the JWT token.

I've tried retrieving the user directly from the JSON token via this.$store.commit('setAuthUser', response.data.user) and response.data.user.username

Login.Vue

axios.post(this.$store.state.endpoints.obtainJWT, payload)
                    .then((response) => {
                        this.$store.commit('updateToken', response.data.token)
                        this.$store.commit('setAuthUser', response.data.user) -------This line is not working
                        console.log(response.data)
                    })

store.js

export default new Vuex.Store({
    state: {
        authUser: {},
        isAuthenticated: false,
        jwt: localStorage.getItem('token'),
        endpoints: {
            obtainJWT: 'http://127.0.0.1:8000/get-token/',
            refreshJWT: 'http://127.0.0.1:8000/refresh-token/',
            baseUrl: 'http://127.0.0.1:8000/main/api/',
        }
    },

    mutations: {
        setAuthUser(state, {
            authUser,
            isAuthenticated
        }) {
            Vue.set(state, 'authUser', authUser)
            Vue.set(state, 'isAuthenticated', isAuthenticated)
        },
        updateToken(state, newToken) {
            localStorage.setItem('token', newToken);
            state.jwt = newToken;
        },
        removeToken(state) {
            localStorage.removeItem('token');
            state.jwt = null;
        }
    }
});

Expected: Properly retrieved user and stored in Vuex with setAuthUser mutator

Actual: Error Cannot destructure property 'authUser' of 'undefined' or 'null'.

Joe Howard
  • 307
  • 5
  • 27
  • 1
    A JWT cannot - and should not - be decrypted on the front end. If you want to return the user from the token you would have to parse it on the backend with `jwt.verify` and send the user property to the front end once it's parsed. – Len Joseph May 13 '19 at 19:04
  • So should I set up an endpoint for returning the current logged in user? – Joe Howard May 13 '19 at 19:07
  • 1
    The first comment here provides a good example of destructuring the JWT object https://stackoverflow.com/questions/33451298/nodejs-retrieve-user-infor-from-jwt-token In my own application I hit a separate endpoint to return the logged-in user to vuex, but this is how you would do it from a JWT. – Len Joseph May 13 '19 at 19:08

0 Answers0