I am building an authentication system for a website in NodeJS using Express, Passport and jsonwebtoken. I have searched everywhere but I cannot find the solution to a problem.
Right now I have an authentication controller:
module.exports = function() {
var strategy = new BearerStrategy(params, function(payload, done) {
var decodedToken = jwtDecode(payload)
db.default.Account.find({where: {id: decodedToken.id}}).then(account =>{
if (account) {
return done(null, {
id: account.id,
role: account.role
})
} else {
return done(new Error("User not found"), null)
}
})
})
passport.use(strategy)
return {
initialize: function() {
return passport.initialize()
},
authenticate: function() {
return passport.authenticate("bearer", cfg.jwtSession)
}
}
}
In which I use a BearerStrategy and this code works, since my /login route crates a token for the user and returns that token
accountController.post("/login", function(req, res) {
if (req.body.email && req.body.password) {
var accEmail = req.body.email
var accPassword = req.body.password
db.default.Account.find({where: {email: accEmail, password:
accPassword}}).then(account =>{
if (account) {
var payload = {
id: account.id,
role: account.role
}
var token = jwt.sign(payload, cfg.jwtSecret)
console.log(token)
res.status(200).json({
token: 'Bearer ' + token
})
} else {
res.sendStatus(401)
}
})
} else {
res.sendStatus(401)
}
})
If I use Postman to send an HTTP request trying to access the route /account and I set as header the token created everything works fine.
accountController.get('/account', auth.authenticate('bearer', { session: false }), function(req, res){
res.status(200).render('pages/homepage')
})
The question I haven't been able to answer is: It is not enough to send the token back with res.json({token: token}), the token needs to be stored somewhere, right? How should I store the token using a RestAPI, and moreover, how should I send the token from the client-side inside the HTTP header in each request?
I am open to suggestions on how to make this connection between storing and sending the JWT (since generation and validation of the JWT work) thank you