Upon logging in, my page sends the login and password information to the backend, receives a jwt token in return, saves it to the cookies, and redirects to /home.
However, there seems to be an issue with the authentication check on the /home route. When checking immediately after login, the token is undefined and no redirect occurs
Here is the router configuration:
const routes = [
{
path: '/login',
component: Login,
beforeEnter: (to, from, next ) => {
if(isAuthenticated()) next("/home");
else next()
}
},
{
path: '/',
redirect: '/login'
},
{
path: '/home',
component: Menu
}
];
router.beforeEach((to, from, next) => {
if(!isAuthenticated() && to.path !== '/login') next('/login');
else next();
});
This is the authentication check middleware function:
export const isAuthenticated = () => {
const token = getCookie("token");
console.log(token)
if (token) {
const jwt = parseJwt(token)
if (Date.now() >= jwt.exp * 1000) {
console.log('unauthenticated - expired token')
return false
} else {
console.log('authenticated - valid token')
return true
}
} else {
console.log('unauthenticated - no token in cookie')
return false
}
}
const getCookie = (name) => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
const parseJwt = (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);
}
The following is the store action for logging in:
login({ commit }, loginRequest) {
commit("LOGIN_PENDING")
axios.post("/api/login", loginRequest)
.then(
(response) => {
document.cookie =`token=${response.data.token}`;
commit("SET_TOKEN", response.data.token);
commit("LOGIN_COMPLETE");
},
(error) => {
if(error.response.status==401) {
commit("SET_INVALID_LOGIN_CREDENTIALS", true);
commit("LOGIN_COMPLETE");
}
}
)
}
How can I ensure that the token is saved to the cookie (
document.cookie =<code>token=${response.data.token}
;)
I would greatly appreciate any assistance!