In the Part-1 we have learned steps to build a VueJS application authentication by using an access token(Jwt token). This is the continuation article, here we are going to understand the steps for implementing refresh token and using access token in the request header to call secured API.
NestJS(Nodejs) Todos API:
In Part-1 we discussed steps to set up the Nestjs API. In that API we have a secured endpoint called 'Todos'. In the next step, we are going to consume this 'Todo' API from our angular application.
http://localhost:3000/todos
Access Token Authorization To Access Secured Endpoint:
Now let's try to access the secured endpoint 'todos' mentioned above in our 'Dashboard' page.
Now for this todos, we are going to create another module file like 'todo.js'.
src/store/modules/todo.js:
import axios from 'axios'; const state = () => ({ todos :[] }); const getters = { getAlltodos(state){ state.todos; } }; const actions = { async getAllTodos({commit}){ var response = await axios.get('http://localhost:3000/todos'); if(response && response.data){ commit('setTodos', response.data); } } }; const mutations = { setTodos(state, payload){ state.todos = payload; } }; export default{ namespaced: true, state, getters, actions, mutations }
- (Line: 3-5) The 'state' object will store our 'todos' object.
- (Line: 7-11) In 'getters' object defined a function 'getAllTodos' that return our collection of 'todos'.
- (Line: 13-20) In 'actions' object defined 'getAllTodos' that will call our secured endpoint and save the response data using mutation object.
src/store/index.js:
import { createStore } from "vuex"; import authModule from './modules/auth'; import todoModule from './modules/todo'; const store = createStore({ modules:{ auth:authModule, todo: todoModule } }); export default store;Now update the 'Dashboard' page to trigger the 'actions' in the todo.js store module to invoke the API call.
src/components/Dashboard.vue:(Html Part)
<template> <div> <h1>Dashboard Page</h1> <div>UserName -- {{ gettersAuthData.userName }}</div> <div>Id -- {{ gettersAuthData.userId }}</div> <div> <h6>My Todos</h6> <button type="button" class="btn btn-primary" @click="show()">Show Todos</button> <ul> <li v-for="(t, index) in gettersAllTodos" :key="index"> {{t}} </li> </ul> </div> </div> </template>
- (Line: 8) Create a button registered with the callback method 'show' which will invoke the todos API.
- (Line: 10-12) Binding the todos data.
<script> import { mapGetters, mapActions } from "vuex"; export default { computed: { ...mapGetters("todo",{ gettersAllTodos:"getAlltodos" }), ...mapGetters("auth", { gettersAuthData: "getAuthData", }), }, methods:{ ...mapActions("todo",{ actionsGetAllTodos:'getAllTodos' }), async show(){ await this.actionsGetAllTodos(); } } }; </script>
- (Line: 5-7) The 'mapGetters' registered for todo.js module getters were registered with 'getAlltodos' getter that returns all collection of 'todos'.
- (Line: 16-18) The 'mapActions' registered for todos.js module actions. Here registered 'getAllTodos' action method that will trigger todos API endpoint.
src/shared/jwtInterceptor.js:
import axios from "axios"; import store from '../store/index'; const jwtInterceptor = axios.create({}); jwtInterceptor.interceptors.request.use((config) => { const authData = store.getters["auth/getAuthData"]; config.headers.common["Authorization"] = `bearer ${authData.token}`; return config; }); export default jwtInterceptor;
- (Line: 4) Creating an instance of Axios and assigned to variable 'jwtInterceptor'. Now, 'jwtInterceptor' works exactly as 'Axios'.
- (Line: 6) Configuring interceptor for the 'jwtInterceptor' instance.
- (Line: 7) Fetching token data from the store.
- (Line: 8) Adding an authorization header. So if we make calls using 'jwtInterceptor' the authorization header will be added to the request.
src/store/modules/jwtInterceptor.js:
import jwtInterceptor from '../../shared/jwtInterceptor'; const actions = { async getAllTodos({commit}){ var response = await jwtInterceptor.get('http://localhost:3000/todos'); if(response && response.data){ commit('setTodos', response.data); } } };
- Since we are using our custom Axios instance that is 'jwtInterceptor', so for the request authorization header added automatically.
Refresh Token Flow:
- Refresh Token is a random string key that will be created along with the JWT access token and return to the valid client on successful logging in.
- Now for all subsequent requests will use the access token, but the access token is a short-lived token whereas the refresh token lives more time than the access token.
- On the expiration of the access token, the user instead of authenticating himself again passing his user name and password, the user can send the refresh token.
- The server on receiving a refresh token first validates against the storage(database, cache, etc).
- For a valid refresh token server will create a new access token and refresh token(like when authenticate using user name and password) return it to the user.
Integrate Refresh Token Endpoint:
Now in our interceptor we need to update logic in such a way that if the access token expires then we need to invoke the refresh token endpoint after receiving new 'access' and 'refresh' tokens we need to update them in browser local storage and also need to restore our vuex state management after that we need to invoke our secured endpoint with a valid access token as its authorization header.
NestJS API Refresh Token Endpoint URL:- http://localhost:3000/auth/refreshtoken Payload:{ "access_token":"", "refresh_token":"" }Now let's update our interceptor to call the refresh token endpoint if our access token expires.
src/shared/jwtInterceptor.js:
import axios from "axios"; import store from '../store/index'; const jwtInterceptor = axios.create({}); jwtInterceptor.interceptors.request.use((config) => { const authData = store.getters["auth/getAuthData"]; if (authData == null) { return config; } config.headers.common["Authorization"] = `bearer ${authData.token}`; return config; }); jwtInterceptor.interceptors.response.use( (response) => { return response; }, async (error) => { if (error.response.status === 401) { const authData = store.getters["auth/getAuthData"]; const payload = { access_token: authData.token, refresh_token: authData.refreshToken, }; var response = await axios.post( "http://localhost:3000/auth/refreshtoken", payload ); await store.dispatch("auth/saveTokensToStorage", response.data); error.config.headers[ "Authorization" ] = `bearer ${response.data.access_token}`; return axios(error.config); } else { return Promise.reject(error); } } ); export default jwtInterceptor;
- (Line: 7-15)In the interceptor request, we have implemented a code to add an authorization header to every request which will use this interceptor.
- (Line: 17-42) Here we capture the response of each request. If the request is good we don't interrupt the flow. If the request has failed then we are implementing some of our application logic.
- (Line: 22) Checking that the error response is 401(unauthorized) means either we haven't added any authorization header or our access token might have expired.
- So on token expiration, we will invoke the refresh token endpoint. On receiving a successful response we will store new token data to browser local storage and update our vuex state token data. Using the new access token as an authorization header and reinvoke the failed request.
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information on refresh token implementation in VueJS 3.0 application. I love to have your feedback, suggestions, and better techniques in the comment section below.
sir once access token expired, then if we refresh the page it going to login page,how can refresh token there,simply how can we use interceptor and refresh the token at page loading( i mean like in facebook, in facebook if we login and close browser after sometime ,and if we reopen the same page next day it will not take us to login page we are authenticated using refresh token. how can we implement this please add this too it will help us a lot, in this application it access token is expired and we refresh page it just going to login page but access token expired and if we click button in dashboard then refresh token works, please add refreshing token at page refresh too )
ReplyDeleteHi moses
DeleteTo resolve this issue we need to call refresh token endpoint in the router.js file in 'beforeach' method. Interceptor main goal to add authorization header, so here in this case no need to use interceptor you can use directly axios to invoke the refresh token endpoint.
I have updated git repo for calling refresh token in router.js file check the link below
https://github.com/Naveen512/VueJS3.0-JWT-Authentication/blob/master/src/appRouter.js
i don't know how to express my gratitude,it helped me a lot.god will always with you,thank you
Deletehi sir i have one more doubt ,how can i add "Content-Type : application/json" and
ReplyDeleteAccept : application/json" to the interceptor, please help me
config.headers["your_header_name"]="header_value"
Delete
Deletethank you so much
thanks a lot
ReplyDeleteit was a great help ♥
ReplyDeleteBecause when the token expires it is showing 401 on the network and if I refresh it on the page to give the 401 to each request?
Hi, I cannot find saveTokensToStorage function in store.Please help
ReplyDelete