In this article, we are going to understand the steps for JWT(JSON Web Token) authentication. Here our main focus to fetch the JWT access token to make users log into our VueJS 3.0 application. For maintaining user info we will use Vuex state management.
src/components/Home.vue:
JWT Token:
JSON Web Token is a digitally signed and secured token for user validation. The jwt is constructed with 3 informative parts:
- Header
- Payload
- Signature
Create A VueJS 3.0 Sample Application:
Let's begin by creating a VueJS 3.0 sample application.
Command To Install Vue CLI Globally On Your System
npm install -g @vue/cli
Command To Create A Vue App:
vue create your_app_name
Required NPM Packages:
Need to install the Vue routing library to configure routing into our application.
Command To Install Vue Router Library(For Vue3.0)
npm install vue-router@4
Need to install the Vuex Store library to configure state management to our application
Command To Install Vuex Store Library(For Vue3.0)
npm install vuex@next
Install Axios library to invoke API call's in our application
Command To Install Axios Library
npm install axios
Basic Page Component And Route Configuration:
In this section, we will be going to implement vue js pages and their routes.
Let's use bootstrap design in our sample so add the below CSS reference link in the index.html page of our VueJS application
public/index.html:(Just above closing head tag)
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">Now add the Home component.
src/components/Home.vue:
<template> <div> <h4>Home Page</h4> </div> </template> <script> export default { } </script>Now add the Login Form component.
src/components/Login.vue:(Html Part)
<template> <div> <h4>Login Form</h4> <form> <div class="mb-3"> <label for="txtuserName" class="form-label">User Name</label> <input type="text" class="form-control" id="txtuserName" aria-describedby="emailHelp" v-model="username"/> </div> <div class="mb-3"> <label for="txtPassword" class="form-label">Password</label> <input type="password" class="form-control" id="txtPassword" v-model="password"
/> </div> <button type="button" class="btn btn-primary" @click="login()">Submit</button> </form> </div> </template>
- Here we created a sample login form with model binding properties like 'username' and 'password'.
<script> export default { data(){ return{ username:'', password:'' } }, methods:{ login(){ console.log(this.username, this.password); } } }; </script>
- Here we have model binding properties and the 'login' method.
<template> <div> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <router-link to="/" class="nav-link">Home</router-link> </li> <li class="nav-item"> <router-link to="/login" class="nav-link">Login</router-link> </li> </ul> </div> </div> </nav> <router-view></router-view> </div> </template> <script> export default { name: "App", components: {}, }; </script>
- Here we added a bootstrap menu and also used the 'router-link' vue component for navigation and also used the 'router-view' vue component to render the content.
src/appRouter.js:
import { createRouter, createWebHistory } from 'vue-router'; import Home from './components/Home.vue'; import Login from './components/Login.vue'; const routes =[ {path:'/', component:Home}, {path:'/login', component:Login} ]; export const routeConfig = createRouter({ history: createWebHistory(), routes: routes });Now register our route config file into our main.js file
src/main.js:
import { createApp } from 'vue' import App from './App.vue' import * as appRouter from './appRouter'; const app = createApp(App) app.use(appRouter.routeConfig); app.mount('#app')
A Basic Skeleton Structure Of Vuex State Management:
For accessing token or user data we will maintain it in Vuex State Management along with the browser local storage. So now here we will implement a basic structure of vuex state management in our sample application.
src/store/modules/auth.js:
const state = () => ({ authData: { token: "", refreshToken: "", tokenExp: "", userId: "", userName: "", }, }); const getters = {}; const actions = {}; const mutations = {}; export default{ namespaced:true, state, getters, actions, mutations }
- Here we are separating our states by using modules which means we can maintain the different states of an application as a module. Here we creating authentication as a separate state module into the auth.js file.
- In general state mainly contains objects like 'state', 'getters', 'actions', and 'mutations'.
- Inside of state object, we have created an object called 'authData' which maintains all information about the application authentication.
- Defined to use namespace in the state to avoid the conflict between the method names
src/store/index.js:
import { createStore } from "vuex"; import authModule from './modules/auth'; const store = createStore({ modules:{ auth:authModule } }); export default store;
- Here we registered our auth module, the property name we used to register our module is 'auth'. The 'auth' property name will be used as the namespace while using our store.
src/main.js:
import { createApp } from 'vue' import App from './App.vue' import * as appRouter from './appRouter'; import store from './store/index'; const app = createApp(App) app.use(appRouter.routeConfig); app.use(store); app.mount('#app')
Mock JWT Access Token:
As a front-end developer no need to spend more time onto work on JWT authentication API (using nodejs, .net, java server programs). So let's use a sample JWT token by mocking it in a constant variable in our application, latter we will make a dynamic API call for fetching the Jwt token at the end section of this article.
A sample jwt token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJzdWIiOjEsImlhdCI6MTYwODIwNjE3OSwiZXhwIjozNjAxNjA4MjA2MTc5fQ.BcHKT6ffgvkt0EztkJT35a0Yc7iWF9wkeNxKB4wSJEQ
JWT Decoder:
As we know JWT token encrypted string which contains some information like 'username', 'expiration', and some other claims. So to decode the jwt access token use the below code snippet
src/shared/jwtHelper.js:
export function jwtDecrypt(token) { var base64Url = token.split(".")[1]; var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/"); var jsonPayload = decodeURIComponent( atob(base64) .split("") .map(function(c) { return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); }) .join("") ); return JSON.parse(jsonPayload); }
Implement Logic To Authenticate User Using Access Token:
Using mock jwt access token we will authenticate our user by storing the access token in browser local storage and in vuex state management as well.
Now update auth.js module state object with an additional property like 'loginStatus' this contains a message like authentication success or failure.
src/store/modules/auth.js:(Update 'state' object)
const state = () => ({ authData: { token: "", refreshToken: "", tokenExp: "", userId: "", userName: "", }, loginStatus:"", });Now update the mutations object to update our state in the auth.js module.
src/store/modules/auth.js:(Update 'mutations' object)
import { jwtDecrypt } from "../../shared/jwtHelper"; const mutations = { saveTokenData(state, data) { localStorage.setItem("access_token", data.access_token); localStorage.setItem("refresh_token", data.refresh_token); const jwtDecodedValue = jwtDecrypt(data.access_token); const newTokenData = { token: data.access_token, refreshToken: data.refresh_token, tokenExp: jwtDecodedValue.exp, userId: jwtDecodedValue.sub, userName: jwtDecodedValue.userName, }; state.authData = newTokenData; }, setLoginStatu(state, value){ state.loginStatus = value; } };
- Here in our mutation, we have defined 2 state change methods like 'SaveTokenData' and 'setLoginStatus'.
- (Line: 2) The 'SaveTokenData' method accepts two parameters. The 'state' parameter nothing but our vuex state which will automatically be passed by the framework and the other is the 'data' parameter which is a user-defined input parameter where we passed our data into the method.
- (Line: 4&5) Saving the token and refresh token data in local browser storage, so that they will be available to our application if we close and reopen our application as well.
- (Line: 7) Decrypting the access token using our helper method defined above
- Next updating the state of the 'authData' object.
- (Line: 17-19) Setting the state of the 'loginStatus'.
src/store/modules/auth.js:(Update 'actions' object)
const actions = { async login({commit},payload) { console.log(payload); const data = { access_token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IlRlc3QiLCJzdWIiOjIsImlhdCI6MTYwNDMwOTc0OSwiZXhwIjoxNjA0MzA5ODA5fQ.jHez9kegJ7GT1AO5A2fQp6Dg9A6PBmeiDW1YPaCQoYs", refresh_token: "" } commit('saveTokenData', data); commit('setLoginStatu','success'); }, };
- (Line: 2) Defined action method 'login'. The reason we made this method async because in upcoming steps we will call authentication API which is an async call. This method has input parameter like '{commit}' this command to trigger the mutation which will be automatically passed by vuex and the second parameter is 'payload' user passing data(ex: user credential object).
- (Line: 4) The constant object mocked with the access token.
- (Line: 8) Invoking the mutation method 'saveTokenData'
- (Line: 9) Invoking the mutation method 'setLoginStatus'
src/store/modules/auth.js:(Update getters object)
const getters = { getLoginStatus(state){ return state.loginStatus; } };Now update the logic in Login.vue component to use the auth.js store to authenticate the user.
src/component/Login.vue:
<script> import {mapActions, mapGetters} from 'vuex'; export default { data(){ return{ username:'', password:'' } }, computed:{ ...mapGetters('auth',{ getterLoginStatus:'getLoginStatus' }) }, methods:{ ...mapActions('auth',{ actionLogin:'login' }), async login(){ await this.actionLogin({username:this.username, password:this.password}); if(this.getterLoginStatus === 'success'){ alert('login sucess'); }else{ alert('failed to login') } } } }; </script>
- (Line: 11-13) The 'getters' in the vuex state are used to fetch data. So to consume the getters in our vue component we need to use 'mapGetters' where we have to register our getters methods. The reason behind 'mapGetters' is used in 'computed' properties is that makes our data available with the latest updates.
- (Line: 16-18) The 'actions' in the vuex state are to do async jobs like invoking API calls and then save the results to state by invoking mutations. So to trigger actions from the vue component we need to use 'mapActions' where we register vuex action methods.
- (Line: 19-26) The 'login' method invoked when the user clicks on the login button. Here we first invoking 'actionLogin' which implicitly calls the 'login' action method states. After that checking the authentication state by using 'getterLoginStatus' which implicitly fetches data from the store.
Create A Dashboard Page:
Now let's create a sample user dashboard page where will display some user's data on it.
Now let's create a getter that fetches the 'authData' object in the auth.js module.
src/store/modules/auth.js:(Update getters object)
// code hidden for display purpose const getters = { getAuthData(state){ return state.authData; } };Create a new 'Dashboard' component where we display the user information.
src/components/Dashboard.vue:
<template> <div> <h1>Dashboard Page</h1> <div> UserName -- {{gettersAuthData.userName}} </div> <div> Id -- {{gettersAuthData.userId}} </div> </div> </template> <script> import { mapGetters } from 'vuex' export default { computed:{ ...mapGetters('auth',{ gettersAuthData:'getAuthData' }) } } </script>
- Here fetching the user data using 'getAuthData' getter.
src/components/Login.vue:
async login(){ await this.actionLogin({userName:this.username, password:this.password}); if(this.getterLoginStatus === 'success'){ this.$router.push("/dashboard"); }else{ alert('failed to login') } }Add the new route in the appRoutes.js file.
src/appRoute.js:
import Dashboard from './components/Dashboard.vue' {path:'/dashboard',component: Dashboard}
Navigation Guards:
Navigation guards are used to executing navigation conditionally means if the non-authenticated user tries to access the page that requires authentication then the navigation guards will restrict the user from accessing the page.
In our sample example, the 'Dashboard' component needs user authentication, but if we try to access it without authentication also user able to see this component. So now we need to apply guards to protect our 'Dashboard' component.
In the jwtHelper.js file add a helper method to check the token expiration.
src/shared/jwtHelper.js:
export function tokenAlive(exp) { if (Date.now() >= exp * 1000) { return false; } return true; }
- The method returns 'true' if the token is still active.
src/store/modules/auth.js:
import { tokenAlive } from "../../shared/jwtHelper"; const getters = { // code hidden for display purpose isTokenActive(state) { if (!state.authData.tokenExp) { return false; } return tokenAlive(state.authData.tokenExp); }, };Now add the navigation guard in the appRouter.js file.
src/appRouter.js:
import { createRouter, createWebHistory } from "vue-router"; import Home from "./components/Home.vue"; import Login from "./components/Login.vue"; import Dashboard from "./components/Dashboard.vue"; import store from "./store/index"; const routes = [ { path: "/", component: Home, meta: { requiredAuth: false } }, { path: "/login", component: Login, meta: { requiredAuth: false } }, { path: "/dashboard", component: Dashboard, meta: { requiredAuth: true } }, ]; export const routeConfig = createRouter({ history: createWebHistory(), routes: routes, }); routeConfig.beforeEach((to,from, next) => { if(to.meta.requiredAuth){ const auth = store.getters["auth/isTokenActive"]; if(!auth){ return next({path: '/login'}); } } return next(); });
- Here we can observe the routes new object like 'meta' is added. In this meta-object, we can define any properties. For our scenario, I have added property like 'requiredAuth' of type boolean, to differentiate which routes need authentication.
- (Line: 18) Here we configured a global navigation guard that will execute for all routes before navigating. Inside of it, we added logic like based on 'requiredAuth' property we are checking user authentication and redirection.
Load Token On Application Open:
Now one problem we face is if we reload our application or closes & reopen the application we can observe we are in a logout state because all the data we maintained in the vuex store will be lost. So in this case we need to restore the store state by loading the access token from the browser's local storage.
So let's update our navigation guard to load the access token from the local browser storage.
src/appRoute.js:
routeConfig.beforeEach((to,from, next) => { console.log(store.getters["auth/getAuthData"].token); if(!store.getters["auth/getAuthData"].token){ const access_token = localStorage.getItem("access_token"); const refresh_token = localStorage.getItem("refresh_token"); if(access_token){ const data = { access_token:access_token, refresh_token:refresh_token }; store.commit('auth/saveTokenData',data); } } const auth = store.getters["auth/isTokenActive"]; if(to.fullPath == "/"){ return next(); } else if(auth && !to.meta.requiredAuth){ return next({path:"/dashboard"}); } else if(!auth && to.meta.requiredAuth){ return next({path: '/login'}); } return next(); });
- (Line: 3-13) Loads the access token from the browser store and then updating the store state by populating the user data.
NestJS(Nodejs) Server JWT API:
I have created a NestJS jwt mock API, where you can clone or download my git repository After downloading the repo run the following commands.
Command To Install NestJS CLI:
npm i -g @nestjs/cli
Next, go to the root folder of the repo and run the command to install all the package
Command To Install ALL Packages In our Repository application:
npm install
That's all we have set up a JWT API in our local system for testing, now run the following command to start the application.
Command To Start NestJS APP:
npm run start:dev
Our jwt token endpoint
Url:- http://localhost:3000/auth/login
Payload:-
{
"username":"test",
"password":"1234"
}
note:- payload should be same as above, variable name 'username' and 'password'
don't change them, they are even case sensitive. credentials also use as above
Integrate JWT Authentication Endpoint:
Till now we used mocked jwt token, now we are going to use real Jwt authentication endpoint.
Let's update the 'login' action method in store
src/store/modules/auth.js:(Update login action method)
async login({ commit }, payload) { const response = await axios .post("http://localhost:3000/auth/login", payload) .catch((err) => { console.log(err); }); if (response && response.data) { commit("saveTokenData", response.data); commit("setLoginStatu", "success"); } else { commit("setLoginStatu", "failed"); } }
- Here we replace our mock jwt token with real authentication API.
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information on access token implementation in VueJS 3.0 application. I love to have your feedback, suggestions, and better techniques in the comment section below.
Command To Install Vue CLI Globally On Your System
ReplyDeletenpm install -g @vue/cli :)
Thanks corrected now
Deletethis code can be used for Vue2?
ReplyDeletethere might be issue with breaking changes, but logic you can implement as it is
DeleteGreat article thank you very much!
ReplyDeleteThank you very much, very useful !
ReplyDeleteWondering if the access_token being sniffed in the transaction when calling API, will there be security breach that people can add the access_token to localstorage and impersonal another?
ReplyDelete