VueJs,Axios how to redirect API unauthenticated users to login page in the best practice?
Hello friends,
While Single Page Application’s usage increase day-by-day one another problem also growing on developer’s mind:
Security , authentication ..
How to prevent user see our frontend app while API return unauthenticated response?.
The main problem is, if you are storing any data in user’s computer for checking what user need to see on the frontend , they may change the value and see your app.This is a big deal for Hackers!
In this post I dont want to talk about how to build backend , what is token and other related issues.
I want to write about how you redirect easily your unauthenticated or forbidden users while your Backend returned as unauthenticated or forbidden status (for example status 401 or 403)?.
I have see many code blocks they are using Promise’s catch block for redirect to login page in every API call, it is pain ,If you have multiple APIs in your code base this point will increase your application with redundant codes and every changes on your codes must be done in every API, this is unimportant.
You can add just some lines and fix this with your Axios instance ,
Determine you have Api.js and it contain such type codes :
import axios from 'axios'
import router from "../router";
const Api = axios.create({
baseURL:'http://127.0.0.1:8001/api/'
});export default Api;
You just add few lines as below:
import axios from 'axios'
import router from "../router"; // I assume you have router module
const Api = axios.create({
baseURL:'http://127.0.0.1:8001/api/'
});
// those lines will catch your 401 status returend requests
Api.interceptors.response.use(function (response){
return response;
},function (error)
{
if(error.response.status)
{
localStorage.removeItem('auth'); //if you are using state or //something else to store auth status then remove it regarding your ''choose
router.push('login') // I assume you have login named router
}
});
export default Api;