Answer the question
In order to leave comments, you need to log in
How to do JWT authorization in NodeJs?
I'm trying to do authorization through passport-jwt. I check the user data sent to the server, his username and password and generate a token.
const username = req.body.username
const password = req.body.password
const user = await User.findOne({
email: username
})
if (!user) {
res.status(404).send(`Пользователь ${username} не существует`)
}
const validPassword = await bcrypt.compareSync(password, user.password)
if (!validPassword) {
res.status(401).send("Пароль не верный")
}
const token = jwt.sign({
userId: user._id,
username: user.email
}, jwtKey, {
expiresIn: '1h'
})
const JWTStrategy = require('passport-jwt').Strategy
const ExstractJWT = require('passport-jwt').ExtractJwt
const JWTkey = require('../config.json').secretJWTKey
const User = require('../models/User')
const options = {
jwtFromRequest: ExstractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey: JWTkey
}
module.exports = passport => {
passport.use(new JWTStrategy(options, async (payload, done) => {
const user = await User.findById(payload.userId).select('email id')
if (!user) {
done(null, false)
}
if (user) {
done(null, user)
}
}))
}
api.get('/create_article', passport.authenticate('jwt', {session: false}), mainController.createArticlePage)
Answer the question
In order to leave comments, you need to log in
const token = jwt.sign({
userId: user._id,
username: user.email
}, jwtKey, {
expiresIn: '1h'
})
res.json({ token })
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question