Reputation: 189
I have a simple web application that a user can create an account and login ... whenever a user log in i am generating a json-web-token
for him and storing it on his database object ... im using that token
to authenticate the user when he visits certain routes ( Bearer token on the header ) but the problem is that when the user refreshes the page i lose that token and he have to provide the email and password again to generate another token ... i was thinking about using localStorage
or cookies
but maybe there is a better / commonly used way for this ... any advises would be helpful thanks .
router.post('/user/login' ,async (req,res)=>{
try {
const user = await User.findByCredentials(req.body.email,req.body.password)
const token = await user.generateToken()
res.send({ user, token })
} catch(e) {
res.status(404).send(e)
}
})
axios({
method: "post",
url: "/api/user/login",
data: {
email: email,
password: password
}
})
Upvotes: 3
Views: 9413
Reputation: 12542
The traditional way to use Persistent session(remember me feature) is to use cookies.
You can make set the max age lets say 30 days when logging in.
router.post('/user/login', function(req, res) {
....
req.session.cookie.maxAge = 30 * 24 * 60 * 60 * 1000; // Cookie expires after 30 days
....
});
The logical flow should be:
hash(cookie)
) and store it in DB.Upvotes: 7
Reputation:
Start the session on the first line of your page, and store the login credentials in it. You can do the same for all other pages to be accessed after login.
Upvotes: 0