Consuming JWT in Client side with Vuejs

in utopian-io •  last year  (edited)

Repository

https://github.com/vuejs/vue

What Will I Learn?

  • Consuming JWT API with endpoint
  • Make Authorization in Axios
  • Set-cookie with Vue-cookie

Requirements

Difficulty

  • Intermediate

Tutorial Contents

This tutorial is an advanced tutorial from my tutorial on JWT. you can see how to create a server-side JWT API through this tutorial authentication. I
will use the API that I have created in the previous tutorial. This time I will consume API in client side by using framework Vue.js.

JWT API with Vue

There are several stages that we will do to ready to consume JWT:

  • Saves the token on the client side

Because we will use tokens as authentication, of course, we must save tokens on the client side. the question is where will we store the token?.

Where will we store the token?

There are two options we can do to store tokens. ie using local storage or using a cookie. but in my opinion, to be more secure I will use a cookie. but of course, you can look for other references.

  • Install the vue-cookie plugin
    Because we will deviate tokens in cookies, we need to install vue-cookies. We can install vue-cookie via NPM:

npm install vue-cookie --save

and if you have not installed vue, you can install vue and vue-cookies simultaneously like this:
npm install vue vue-cookie --save

noted: Make sure you have NPM init.

Then you can use it in main.js


import Vue from 'vue'
import VueCookie from 'vue-cookie'
Vue.use(VueCookie )

in this way you can use vue-cookies globally

  • Make Form Login
    After we finish installing vue-cookie, now I will create a compound for login form in App.vue file, I will add a simple login form that will be used for user authentication.
<template>
  <div id="app">
    <h1>Vue JWT Client</h1>
    <form v-on:submit.prevent="onSubmit">
      <input type="email" name="email" v-model="email">
      <input type="password" name="password" v-model="password">
      <input type="submit" name="submit" value="Login">
    </form>
  </div>
</template>
<script>
export default {
  data(){
    return{
      email:'',
      password:''
    }
  }
}
</script>
  • v-on:submit.prevent="onSubmit": We put the submit event on the < form > element. We can create an event by v-on or shorthand '@' (v-on.submit or @submit), we add .prevent
    We add .prevent because of the nature of the submit is to request to the server. we do not want to do that because we will use Asynchronus with Axios. onSubmit is a function name that declared in properties methods (). We will create the function in the next section.
  • v-model="email" and v-model="password": For input binding we can use v-model and create local variable in data(). So, the name of the v-model must be the same as the variable in the data.

Example:


 data(){
    return{
      email:'',
      password:''
    }
  }

Request XHR with AXIOS

We will request ajax to the server with the endpoint we created earlier in the server.

  1. Login http:/localhost:3000/api/login

  2. Get User http:/localhost:3000/api/users

  3. Profile http:/localhost:3000/api/profile

  • Install Axios
    We need to install Axios via NPM:
    npm install axios
    After we successfully install axios we can use it locally and globally.
  1. locally
    import axios from 'axios'
    You can import axios only in the files you want to use axios. in this tutorial, I'm using it in app.vue.

  2. Globally


import Vue from 'vue'
import axios from 'axios'
Vue.use(axios );

You can import axios in main.js and use Vue.use (axios), this way you do not need to import them one by one in each component.

noted: using globally may affect the speed.

You can see more details in my tutorial on axios and vue

  • Post Data with API JWT
    We will create a function for post data with axios. the function we have created in the < form v-on:submit.prevent="onSubmit" >,onSubmit (). I will use axios locally so I need to import in the component which i will use. The endpoint we will use is Login http:/localhost:3000/api/login

Example:


  onSubmit(){
      axios.post('http:/localhost:3000/api/login', {
            email: this.email,
            password: this.password
          })
          .then(res=>{
            this.$cookie.set('token',res.data.token);
          })
          .catch(err=>{
            console.log(error);
          });
    }

  • axios.post(): We can use the post() to post to the endpoint we are headed. we need two mandatory parameters.

1. The first parameter: The first parameter is the URL or endpoint to be addressed. for our login API endpoint is HTTP:/localhost:3000/api/login.
2. The Second parameter: The second parameter is the object that contains the key and value we will post to the endpoint.in this tutorial key and value, we will post is {email: this.email, password: this.password. The key is email and password. The value is this.email and this.password. We use v-model that has binding input with the local variable, therefore we need to access the local variable in data (). to access it, we just need to add this.

  • this.$cookie.set('token',res.data.token);: We will save the result from post data to endpoint http:/localhost/api/login, to save we can use the set () method, the set method has two mandatory parameters namely key and value. The key is 'token' and the value is obtained from res.data.token. The res comes from the callback function
    .then(res=>{}. If we look at the inspect element in the response section we can see the results of the API:
    Screenshot_7.png

  • Get User Data with API JWT
    I will create a function to retrieve user data from endpoint Get User http:/localhost:3000/api/users. I will put the function in the on-click event on the < button v-on:click="getuser()" >Get user< /button >.

Example:


getuser(){
      axios.get('http:/localhost:3000/api/users', {
           'headers': { 'Authorization': this.$cookie.get('token') }
          })
          .then(res=>{
            console.log(res)
          })
          .catch(err=>{
            console.log(error);
          });
    }

  • axios.get(): We can use the get() to Get data from the endpoint we are headed. Because we need a token to access the endpoint 'http:/localhost:3000/api/users', We need two parameters.
    1. The first parameter: The first parameter is the URL or endpoint to be addressed. for our login API endpoint is HTTP:/localhost:3000/api/users.
    2. The second parameter: The second parameter is optional. because we need to pass the token to API access. we need to pass it in headers 'headers': { 'Authorization': this.$cookie.get('token') }, The key is 'Authorization', and the tokens can be found in the cookie by this.$cookie.get('token').
  • .then(res=>{}: We can see the result in the callback function in the res object.

Screenshot_4.png

  • Get User Profile with API JWT
    I will create a function to retrieve user data from endpoint Get User Profile http:/localhost:3000/api/profile. I will put the function in the on-click event on the < button v-on:click="profile()" >Get Profile< /button >.

Example:


profile(){
      axios.get('http:/localhost:3000/api/profile', {
           'headers': { 'Authorization': this.$cookie.get('token') }
          })
          .then(res=>{
            console.log(res)
          })
          .catch(err=>{
            console.log(error);
          });
    }

  • axios.get(): We can use the get() to Get data from the endpoint we are headed. Because we need a token to access the endpoint 'http:/localhost:3000/api/profile', We need two parameters.
    1. The first parameter: The first parameter is the URL or endpoint to be addressed. for our login API endpoint is HTTP:/localhost:3000/api/profile.
    2. The second parameter: The second parameter is optional. because we need to pass the token to API access. we need to pass it in headers 'headers': { 'Authorization': this.$cookie.get('token') }, The key is 'Authorization', and the tokens can be found in the cookie by this.$cookie.get('token').
  • .then(res=>{}: We can see the result in the callback function in the res object.

Screenshot_5.png

Note: make sure the server nodes and mongod databases you have run, as long as you interact with the endpoint or API that we created in the previous tutorial, if you are confused you can follow some tutorials below.

Screenshot_6.png

Curriculum

API JWT

Vue.js

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thank you for your contribution.
I generally liked your work, I would though advise you the following for your upcoming contributions:

  • better review your post for English mistakes and mis-written sentences as those could lose the focus of author.
  • you have re-used many content from your prior post about jQuery, including screenshots. I would strongly advise against doing that and posting original content every time even though content can somewhat be reused.
  • include a github repository that contains the code that you made in this post here, and provide the link at the end of the post. This would be helpful for your readers to be able to simply try to run and re-use your work.
    Looking forward to your upcoming tutorials.

Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you @mcfarhat , i'll do better for utopian..

Hey @alfarisi94
Thanks for contributing on Utopian.
We're already looking forward to your next contribution!

Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!