I am relatively new to the world of web development, so please forgive me if my question is not articulated clearly or if the solution seems obvious.
Essentially, I am looking to implement JWT authentication for my users using axios, vue.js, and JWT itself. My goal is to access a secure route:
router.post('/secureroute', checkAuth, (req, res) => {
res.status(200).json({
message: 'all ok'
})
});
To achieve this, I have created a check-auth.js file:
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization.split(" ")[1];
console.log(token);
const decoded = jwt.verify(token, process.env.SECRET_KEY);
next();
} catch (error) {
return res.status(401).json({
message: 'Auth failed'
})
}
next();
}
A snippet from my Login.vue component:
methods: {
login() {
if (!this.username) this.alertUsername = true;
if (!this.password) this.alertPassword = true;
axios
.post("/user/login", {
username: this.username,
password: this.password
})
.then(res => {
localStorage.setItem("usertoken", res.data.token);
if (res.data.token) {
console.log("Success");
router.push({ name: "start" });
} else {
this.alertWrong = true;
}
this.username = "";
this.password = "";
})
.catch(err => {
console.log(err);
});
this.emitMethod();
}
While testing with Postman and an authorization header, everything appears to be functioning correctly. However, despite numerous attempts and extensive research online, I am still unable to figure out how to successfully pass the JWT as an authorization header in my actual website project. I understand that it can be done with axios, but I am struggling to implement it in my specific case.