Reputation: 109
I want to protect my routes by adding a middleware 'checkAuth'. This middleware checks the validity of a jwt token. I'm using Express router.
But I don't understand how to do that.
My checkAuth middleware :
module.exports = (req, res, next) => {
let token = req.headers.authorization.split(" ")[1];
try {
jwt.verify(token)
console.log("ok")
}catch (e) {
res.status(403)
}
next();
}
Thank you !
Upvotes: 0
Views: 569
Reputation: 14904
Create a new function called "verifyToken"
I suggest to promisfy it. So you can use it in an async
function in combination with await
function verifyToken(token){
return new Promise((res, err) => {
jwt.verify(token, "secret key", (err) => {
if (err) rej(err)
res(true)
})
})
}
Its promise based. Now you just pass your token to the function it resolves to either true or false:
module.exports = async (req, res, next) => {
let token = req.headers.authorization.split(" ")[1];
try {
await verifyToken(token);
console.log("ok")
}catch (e) {
res.status(403)
}
next();
}
Upvotes: 0
Reputation: 345
Assuming you are using jsonwebtoken, you are missing the "secret" string.
According the documentation that's how you should do.
when creating token:
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
You could also pass expiration time:
jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: 60 * 60 });
for validating:
There a couple of ways you could do it. But you should need the same secret string to validate that you used for signing in. Also you need to assign a variable to jwt.verify or call it with a callback in order to access the decoded data, such as user Id and so on.
// verify a token symmetric - synchronous
var decoded = jwt.verify(token, 'shhhhh');
console.log(decoded.foo) // bar
// verify a token symmetric
jwt.verify(token, 'shhhhh', function(err, decoded) {
console.log(decoded.foo) // bar
});
// invalid token - synchronous
try {
var decoded = jwt.verify(token, 'wrong-secret');
} catch(err) {
// err
}
// invalid token
jwt.verify(token, 'wrong-secret', function(err, decoded) {
// err
// decoded undefined
});
Upvotes: 1