I am learning how to do a JWT authentication process with React and NodeJS( Express). I used postman to execute the following function
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
// Secret key used to sign the tokens
const secretKey = '/Phc{m=MG$nv)UNb&j8k?djaRD)-FQ/3QK,aYT}9a/):FmSk2H';
// Verify token function
function verifyToken(token) {
try {
const decoded = jwt.verify(token, secretKey);
return decoded; // Token is valid
} catch (error) {
return null; // Token is invalid
}
}
// Route for token verification
router.post('/verifyToken', (req, res) => {
const { accessToken } = req.body;
if (!accessToken) {
return res.status(400).json({ error: 'Access token is required' });
}
const decodedToken = verifyToken(accessToken);
if (decodedToken) {
// Token is valid, send success response
return res.json({ isValid: true });
} else {
// Token is invalid, send error response
return res.json({ isValid: false });
}
});
// Export the router
module.exports = router;
We initialize the route in the entry file of our node app
const verifyTokenRouter = require('./routes/VerifyToken')
app.use("/", verifyTokenRouter)
// Import necessary modules
const express = require("express");
const app = express();
const cors = require("cors");
const db = require('./models');
// Middleware
app.use(express.json());
app.use(cors({
origin: 'http://localhost:3000', // Allow requests only from http://localhost:3000
credentials: true // Allow cookies to be sent with the request
}));
With postman the request works just fine , but I have a function to automatically take our cookie and execute verifyToken via axios , however baffling enough it fails because it cannot find the cookie for in my document
useEffect(() => {
// Function to retrieve the value of a cookie by name and domain
function getCookie(name, domain) {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Check if this cookie matches the desired name and domain
if (cookie.startsWith(name + '=') && cookie.includes(`Domain=${domain}`)) {
// Return the value of the cookie
return cookie.substring(name.length + 1);
}
}
// Return null if the cookie is not found
return null;
}
// Retrieve the access token cookie from localhost domain
const accessToken = getCookie('accessToken', 'localhost');
// Example usage
if (accessToken) {
// Make a request to your server's API endpoint for token verification
axios.post('http://localhost:3001/auth/verifyToken', { accessToken })
.then(response => {
const isValid = response.data.isValid; // Assuming the server returns the verification result
console.log('Token verification result:', isValid);
if (isValid) {
console.log('Sign In successful');
} else {
console.log('Sign In failed');
}
})
.catch(error => {
console.error('Error verifying token:', error);
});
} else {
console.error('Access token cookie not found');
}
}, []);
So just to clarify again only the last block of code fails it returns the else error of App.jsx:48 Access token cookie not found
so getCookie accessToken fails for some reason ? Initially I thought it may not know the domain so I added this line if (cookie.startsWith(name + '=') && cookie.includes(
Domain=${domain}`)) I also tried to remove the name of the cookie and identify by the domain name alone but i still have the same error.
I’m really not sure what I am doing wrong
I searched for similar issues but not one of them really match my case.