I have started using NodeJS with Express JS and PassportJS and JWT for User Authentication. I am able to authenticate the user and generate JWT Token. I am using Bootstrap for my front-end.
By using Postman I am able to get the token and put it in the next request header and it is working fine.
But how do I do this in HTML Pages using JavaScript?
- JavaScript to get response body or response headers
- JavaScript to set request header with JWT Token
Here is the snippet to store data in SessionStorage
:
sessionStorage.setItem('token', 'token-abcd1234');
var token = sessionStorage.getItem('token');
I have a mechanism to invalidate the token on logout
by putting them in a DB.
Let me know if I am missing any pattern or missing anything.
Note: I am using login.html which has a form with a username and password. AJAX is not used.
Login Page
<body>
<div class="container">
<h3>Login</h3>
<div class="jumbotron col-sm-6">
<form class="form-horizontal" action="/login" method="POST">
<div class="form-group">
<label class="control-label col-md-2" for="email">Email:</label>
<div class="col-md-4">
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="password">Password:</label>
<div class="col-md-4">
<input type="password" class="form-control" id="password" placeholder="Enter password" name="password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
</div>
</body>
NodeJS Route
router.get('/login', function(req, res, next) {
res.render('login');
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
console.log(err);
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});