0

Хотел сделать чтобы некоторые ветки API сервера на node+express имели защиту токеном и были доступны только авторизованым пользователем но постоянно получаю

{
    "message": "auth failed"
}

Вот код проверки токена:

    const jwt = require('jsonwebtoken')

module.exports = (req,res,next) => {
    try {
        const token = req.headers.authorization.split(" ")[1]
        console.log(token)
        const decoded = jwt.verify(token, 'shh')
        console.log(decoded)
        req.userData = decoded
        next()  
    } catch (error) {
        return res.status(401).json({
            message: 'auth failed'
        })
    }
}

console.log(token) выводит нормально токен а вот console.log(decoded) ничего не выводит и поэтому мне кажется что проблема в нем но я смотрю как в документации jsonwevtoken так и у меня.Так в чем проблема?

Код в котором идет проверка:

router.post('/',checkAuth,upload.single('productImage'), (req, res, next) => {
    console.log(req.file)
    const product = new Product({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price,
        productImage: req.file.path
    })
    product.save()
        .then((result) => {
            res.status(201).json({
                createdProduct: result
            })
        })
        .catch(err => {
            console.log(err)
            res.status(500).json({
                error: err
            })
        })
})

Ошибка

{ JsonWebTokenError: invalid signature
    at X:\projects\Brand-server\node_modules\jsonwebtoken\verify.js:122:19
    at getSecret (X:\projects\Brand-server\node_modules\jsonwebtoken\verify.js:76:14)
    at Object.module.exports [as verify] (X:\projects\Brand-server\node_modules\jsonwebtoken\verify.js:80:10)
    at module.exports (X:\projects\Brand-server\src\middleware\check-auth.js:7:23)
    at Layer.handle [as handle_request] (X:\projects\Brand-server\node_modules\express\lib\router\layer.js:95:5)
    at next (X:\projects\Brand-server\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (X:\projects\Brand-server\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (X:\projects\Brand-server\node_modules\express\lib\router\layer.js:95:5)
    at X:\projects\Brand-server\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (X:\projects\Brand-server\node_modules\express\lib\router\index.js:335:12)
    at next (X:\projects\Brand-server\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (X:\projects\Brand-server\node_modules\express\lib\router\index.js:174:3)
    at router (X:\projects\Brand-server\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (X:\projects\Brand-server\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (X:\projects\Brand-server\node_modules\express\lib\router\index.js:317:13)
    at X:\projects\Brand-server\node_modules\express\lib\router\index.js:284:7 name: 'JsonWebTokenError', message: 'invalid signature' }
::ffff:127.0.0.1 - - [12/Jun/2018:18:43:21 +0000] "POST /products HTTP/1.1" 401 25 "-" "PostmanRuntime/7.1.5"
4
  • Ну так вы посмотрите содержимое error, в нём ответ на ваш вопрос
    – andreymal
    12 июн 2018 в 18:26
  • Обвновил вопрос.Все равно не понял что значит не верная сигнатура?Я же сделал как в документации) 12 июн 2018 в 18:48
  • Очевидно jwt.verify считает ваш токен невалидным
    – Alexey Ten
    12 июн 2018 в 19:06
  • Спасибо)Исправил 12 июн 2018 в 19:11

1 ответ 1

1

Срок действия токена был истек))Нужно было заново залогинится и тогда создался новый токен и все заработало.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.