I use JWT for auth.
The auth will be a middleware:
const jwt = require('jsonwebtoken');
require('dotenv').config();
module.exports = (req, res, next) => {
const token = req.header("auth-token");
if (!token) return res.status(401).send("Missing token. Access denied");
try {
const decoded = jwt.verify(token, process.env.jwtKey);
req.user = decoded;
next();
} catch (err) {
console.log(err);
res.status(400).send('Invalid token.');
}
};
now when I get an token and use it in header "auth-token" and making a get or post request with the auth middleware its allways gives me "JsonWebTokenError: invalid signature"
I use the middleware like this:
router.get('/:id', auth, async (req, res) => {
const user = await User.findOne({
_id: req.params.id,
});
if (!user) return res.status(404).send('User not found');
res.send(user);
})
here is where the token is generated
router.post('/', async (req, res) => {
//check for validation errors
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
let user = await User.findOne({ email: req.body.email });
if (!user) return res.status(404).send("Invalid email or password");
const validPassword = await bcrypt.compare(req.body.password, user.password);
if (!validPassword) return res.status(400).send("Invalid email or password");
res.json({ token: user.generateAuthToken(), status: "User is logged in" })
});
const validate = (req) => {
const schema = Joi.object({
email: Joi.string().min(6).max(255).email().required(),
password: Joi.string().min(6).max(255).required(),
});
return schema.validate(req);
};
module.exports = router;
You can see the auth middleware is used when I make the request GET
At JWT.io debugger when I put the token its says its ok... so whats worng?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…