Reputation: 77
I am currently designing a simple website, where users can log in as a normal user or as an admin. Right now I am coding out the portion for when the user wants to go to an admin only web page, and the server will retrieve the jwt token stored in the local storage on the web browser to validate it.
This is what the local storage looks like
Here is the code for retrieving the jwt token
var verifyFn = {
verifyToken: function (req, res, next) {
const authHeader = localStorage.getItem("jwt_token");
console.log("THIS IS THE HEADER")
console.log(authHeader)
if (authHeader === null || authHeader === undefined ){
return res.status(401).send({ message: 'not authenticated BEARER TOKEN ISSUE' });
}
const token = authHeader
console.log("NEW TOKEN")
console.log(token)
jwt.verify(token, config.jwt.secret, { algorithms: ['HS256'] }, (err, decoded) => {
if (err) return res.status(401).send({ message: 'not authenticated' });
req.decodedToken = decoded;
console.log("DECODED TOKEN: " + req.decodedToken)
next();
});
}
However, whenever I try to run the server and browse to the admin page, there will be an error saying 'localstorage is not defined'. As such, I am not sure about how I can retrieve the jwt_token from the web browser to the server back end.
Upvotes: 1
Views: 1926
Reputation: 434
A server has no access to the browser's localStorage
object, as it is accessible from the client only, and does not exist in the server context.
What is usually done is sending the token in an Authorization
header. It looks like you are using Node
, so consider the following example request using the fetch API on the client:
const jwtToken = localStorage.getItem('jwt_token')
fetch('your-api-url', {
method: 'request method here',
headers: {
Authorization: `Bearer ${jwtToken}`
},
body: JSON.stringify(your request body here)
}).then(response => ...)
In the server, you can then get the JWT token by looking at the request headers, something like this:
var verifyFn = {
verifyToken: function (req, res, next) {
let authHeader = req.headers['Authorization']
// the auth header will have Bearer prepended, so remove it
authHeader = authHeader.replace('Bearer ', '')
console.log("THIS IS THE HEADER")
console.log(authHeader)
if (authHeader === null || authHeader === undefined ){
return res.status(401).send({ message: 'not authenticated BEARER TOKEN ISSUE' });
}
const token = authHeader
console.log("NEW TOKEN")
console.log(token)
jwt.verify(token, config.jwt.secret, { algorithms: ['HS256'] }, (err, decoded) => {
if (err) return res.status(401).send({ message: 'not authenticated' });
req.decodedToken = decoded;
console.log("DECODED TOKEN: " + req.decodedToken)
next();
});
}
Upvotes: 2