Just trying to do a basic implementation of signing and verifying a JSON web token with an Express server, but the "verify" function keeps returning an "Invalid token" error.
When pasting the generated token from the '/' route into the jwt.io debugger it initially says 'invalid signature' but when I check the 'secret is base64 encoded' checkbox, the debugger validates the signature, so I've tried base64 encoding/decoding my secret on the signing and verifying end, but nothing worked.
I am currently performing the requests using a VS code extension named "REST Client" that allows you to make requests using a ".rest" or ".http" file, and I am passing "Bearer [token]" to the Authorization header manually. I was also testing using Postman and received the same error. The app is fetching the header via both methods as expected.
const express = require('express')
const jwt = require('jsonwebtoken')
const app = express()
app.use(express.json())
app.get('/', (req, res) => {
const user = {
username: 'test1234',
email: '[email protected]',
admin: false
}
const secret = 'secret'
jwt.sign(user, secret, (err, token) => {
req.token = token
res.send(token)
})
})
app.get('/verify', (req, res) => {
// Bearer <token>
const authHeader = req.headers.authorization
console.log(authHeader)
if(authHeader) {
const token = authHeader.split(' ')[1]
const secret = 'secret'
const userData = jwt.verify(token, secret)
res.send(userData)
} else {
return res.send('Please provide a token.')
}
})
app.listen(3000, () => console.log('Server listening on http://localhost:3000 ...'))
I'm expecting the payload (userData) to be returned from the '/verify' route, but instead get an "invalid token" error.
Update: The problem was that I was wrapping the value of my authorization header in quotes, ex. Authorization: "Bearer [token]", when it should have not been in quotes, ex. Authorization: Bearer [token].