D
D
Daniil Yakovlev2021-01-17 13:46:20
Node.js
Daniil Yakovlev, 2021-01-17 13:46:20

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'
        })

Passport checks for the presence of the 'Bearer token' field in the Authorization
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)
        }
    }))
}

I have protection on the right route.
api.get('/create_article', passport.authenticate('jwt', {session: false}), mainController.createArticlePage)

When testing through Postman, everything works as it should.

However, I don't know how to pass this token to the client so that it can then send it to the server for verification. How can I push it into Authorization before it opens the page I need

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel, 2021-01-17
@PAVLIK_GYRA

const token = jwt.sign({
            userId: user._id,
            username: user.email
        }, jwtKey, {
            expiresIn: '1h'
        })
res.json({ token })

at the front you get data, you take it, you put it in localStorage.setItem('auth', token). When requesting the desired page, you send it in the options to fetch or axios in the header {Authorization: token}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question