I’m following this article https://medium.com/@favalcodes/authentication-and-authorization-in-node-js-15142e33f1d7.
I’m using json web tokens to authenticate users. The server.js code is below.
I’ve debugged the code and it’s hitting the app.get(‘profile, authenticateToken….) function and authenticates the user when they log in but the issue I have is that it doesn’t seem to be triggering
res.sendFile(`${base}/profile.html`);
and it’s not loading up the profile.html page.
I think the reason is because when I make the get request from the client login.js file it is expecting something to come back. So for example in login.js I have an ajax request:
login.js
$.ajax({
url: '/profile',
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token
},
success: function(response) {
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status === 401 || jqXHR.status === 403) {
alert('Access denied');
} else {
alert('An error occurred: ' + textStatus);
}
}
});
And so when performing the get request, when the user is successfully authenticated it is coming back to “success” here and not loading up the profile.html page from server.js
server.js
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
const secretKey = 'secretKey'; //You can use anything here as your secret key
app.post('/login', (req, res) => {
// Authenticate user
const user = { id: 1, username: 'example' };
const token = jwt.sign(user, secretKey, { expiresIn: '1h' });
res.json({ token });
});
//This is a function to authenticate the token if it's a valid token
//This function serves as a middleware
function authenticateToken(req, res, next) {
const token = req.headers['authorization'];
if (token == null) return res.sendStatus(401);
jwt.verify(token, secretKey, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
// This route authorizes the user if the token used is valid
app.get('/profile', authenticateToken, (req, res) => {
try {
res.sendFile(`${base}/profile.html`);
} catch (error) {
res.status(401).send('Unauthorized')
}
});
For html pages that don’t need authentication, eg. for an “About Us” page, I can just use windows.location.href or just href and then hit the server with
app.get('/about', (req, res) => {
res.sendFile(`${base}/about.html`);
});
And that seems to load the page – but when authenticating, it doesn’t send the page back.
Thanks.