I read in some security blog that storing a token in localstorage is unsafe so what i want to do is to store the token in the vuex storage, and all the api call will include that token in all following request.
But I am not able to access the token in the first place during successful login, what I want to do is to store the token in the vuex storage for the first time, I thought of sending the token to the body of the response but it will be a vulnerable method so I am sending it in the header["authorization"].
below are my user.js and login.vue file respectively.
router.post('/login', function (req, res, next) {
const {
UserName,
Password
} = req.body;
if (UserName.length == 0 || Password.length == 0) {
res.status(400).json({
message: 'Email or Password is empty',
});
} else {
login_pool.query(
'SELECT * FROM authentication WHERE user_name = ($1) and password = crypt(($2), password)',
[UserName, Password],
(err, results) => {
if (err) {
throw err;
} else if (results.rows.length == 1) {
// On Successful Login
const token = jwt.sign(
{
user_name: results.rows[0].user_name,
full_name: results.rows[0].full_name,
phone_number: results.rows[0].phone_number,
},
btoa(process.env.TOKEN_SECRET), // converting token_secret to base 64
{ expiresIn: '1800s' },
{ algorithm: 'HS256' },
(err) => {
if (err) {
res.status(400).json({
message: 'Not able to create a token',
});
console.log(err);
}
}
);
res.header('Authorization', `Bearer ${token}`);
res.status(201).json({
message: results.rows[0].full_name + 'logged in.',
});
console.log(results.rows[0].full_name + 'Just Logged In. ');
} else {
login_pool.query(
'SELECT * FROM authentication WHERE user_name = ($1)',
[UserName],
(errUser, resultUser) => {
if (resultUser.rows.length != 1) {
res.status(400).json({
message: 'User with this email does not exist',
});
} else {
res.status(400).json({
message: 'Password is not correct',
});
}
}
);
}
}
);
}
});
LoginSubmit() {
this.axios
.post(
"http://127.0.0.1:3000/users/login",
{
UserName: this.UserName,
Password: this.Password,
},
{
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
Accept: "application/vnd.api+json",
},
}
)
.then(
(res) => {
// successful login
console.log(res.headers); // authentication header not present here
this.Error = "";
console.log(this.axios.defaults.headers.common); // authentication header not present here
},
(err) => {
console.log(err.response.data.message);
this.Error = err.response.data.message.replace(/"/g, "");
}
);
},