Vue.js JWT Patterns

Joshua Bemenderfer

JWT’s or JSON Web Tokens are a popular method of storing verifiable session state safely on the client without the need for stateful servers. They’ve grown in popularity immensely lately along with the rise of “serverless” web applications. JWTs are a core part of your application’s state, but are both a token and a piece of parsable data. So how do we use them in both ways? Here are a couple patterns that can make working with JWTs in Vue.js a breeze.

Throughout this guide we'll be pretending we have a API endpoint that responds with a JWT as a string at GET http://localhost/vuejs-jwt-example/auth?u=username&p=password. You'd want to replace this with your own implementation.

How to persist the JWT across sessions is left to you, just be aware of the dangers of storing sensitive data in localStorage!

Without Vuex

Probably the most important recommendation I would make is to never store a parsed version of the JWT. Having both a string and a parsed object stored separately is setting yourself up for a world of pain.

Instead, use Vue.js’ computed properties to create the object on-demand from the string whenever the string is updated.

With a basic Vue.js component, that might look like this:

<template>
  <div>
    <p>JWT: {{jwt}}</p>
    <p>User ID: {{jwtData.sub}}</p>
    <p>Issuer: {{jwtData.iss}}</p>
    <button @click.native="doSomethingWithJWT()">Do Something</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      jwt: ''
    }
  },

  computed: {
    // this.jwtData will update whenever this.jwt changes.
    jwtData() {
      // JWT's are two base64-encoded JSON objects and a trailing signature
      // joined by periods. The middle section is the data payload.
      if (this.jwt) return JSON.parse(atob(this.jwt.split('.')[1]));
      return {};
    }
  },

  methods: {
    async fetchJWT() {
      // Error handling and such omitted here for simplicity.
      const res = await fetch(`http://localhost/vuejs-jwt-example/auth?u=username&p=password`);
      this.jwt = await res.text();
    },

    async doSomethingWithJWT() {
      const res = await fetch(`http://localhost/vuejs-jwt-example/do-something`, {
        method: 'POST',
        headers: new Headers({
          Authorization: `Bearer: ${this.jwt}`
        })
      });
      // Do stuff with res here.
    }
  },

  mounted() {
    this.fetchJWT();
  }
}
</script>

With Vuex

If you’re using Vuex, you can use a similar pattern based on Vuex actions and getters.

Here’s a example user vuex module that allows you to fetch a JWT and access it in both string and object form.

export const UserModule = {
  state: {
    currentJWT: ''
  },

  getters: {
    jwt: state => state.currentJWT,
    jwtData: (state, getters) => state.currentJWT ? JSON.parse(atob(getters.jwt.split('.')[1])) : null,
    jwtSubject: (state, getters) => getters.jwtData ? getters.jwtData.sub : null,
    jwtIssuer: (state, getters) => getters.jwtData ? getters.jwtData.iss : null
  },

  mutations: {
    setJWT(state, jwt) {
      // When this updates, the getters and anything bound to them updates as well.
      state.currentJWT = jwt;
    }
  }

  actions: {
    async fetchJWT ({ commit }, { username, password }) {
      // Perform the HTTP request.
      const res = await fetch(`http://localhost/vuejs-jwt-example/auth?u=${username}&p=${password}`);
      // Calls the mutation defined to update the state's JWT.
      commit('setJWT', await res.text());
    },
  }
}

Which can be used in a component similar to the one we wrote above like so:

<template>
  <div>
    <p>JWT: {{jwt}}</p>
    <p>User ID: {{jwtSubject}}</p>
    <p>Issuer: {{jwtIssuer}}</p>
    <button @click.native="doSomethingWithJWT()">Do Something</button>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';

export default {
  computed: {
    ...mapGetters([
      'jwt',
      'jwtSubject',
      'jwtIssuer'
    ])
  },

  methods: {
    ...mapActions([
      `fetchJWT`
    ]),

    // The implementation here doesn't change at all!
    async doSomethingWithJWT() {
      const res = await fetch(`http://localhost/vuejs-jwt-example/do-something`, {
        method: 'POST',
        headers: new Headers({
          Authorization: `Bearer: ${this.jwt}`
        })
      });
      // Do stuff with res here.
    }
  },

  mounted() {
    this.fetchJWT({
      // #Security...
      username: 'username',
      password: 'password'
    });
  }
}
</script>

The benefit of the approach shown here is that the JWT iself is only ever stored and updated in string form. (The form used for API requests and validation.) Vue.js’ computed properties allow us to transform that however we need without requiring any extra state synchronization.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#