I have been stuck at JsonWebTokenError: invalid signature
while trying to verify it.
The auth middleware where i am verifying
module.exports.authMiddleware = (req, res, next) => {
const tokenParts = req.headers.authorization.split(" ");
console.log(tokenParts)
// verifying that the token from authorization header is in correct format
if(tokenParts[0] === "Bearer" && tokenParts[1].match(/\S+\.\S+\.\S+/) !== null){
try {
const verification = jsonwebtoken.verify(
tokenParts[1],
PUBLIC_KEY,
{algorithms: ["RS256"]}
)
req.jwt = verification
next()
} catch (error) {
console.log(error)
res.status(401).json({
success: false,
message: "You are not authorized auth"
})
}
} else {
res.status(401).json({
success: false,
message: "You are not authorized",
})
}
}
I have successfuly generated the private and public keys here is the function
const genKeyPair = () => {
const keyPair = crypto.generateKeyPairSync('rsa', {
modulusLength: 4096, // bits - standard for RSA keys
publicKeyEncoding: {
type: 'pkcs1', // "Public Key Cryptography Standards 1"
format: 'pem' // Most common formatting choice
},
privateKeyEncoding: {
type: 'pkcs1', // "Public Key Cryptography Standards 1"
format: 'pem' // Most common formatting choice
}
});
// Create the public key file
fs.writeFileSync("keys/id_rsa_pub.pem", keyPair.publicKey);
// Create the private key file
fs.writeFileSync("keys/id_rsa_priv.pem", keyPair.privateKey);
}
genKeyPair()
When i copy the token that is generated during login or registration and add the private key and public key to jwt.io online with algorithm, i get signature verified
What could possible be the problem?