2017-05-04 146 views
0

我正在用令牌授權,當我跟郵遞員測試,我不斷收到「未授權」登錄後,進入個人資料護照JWT「未授權」節點

登錄代碼:

router.post('/authentication', (request, response, next) => { 
    const email = request.body.email; 
    const password = request.body.password; 

    userModel.getUserByEmail(email, (err, user) => { 
     if (err) throw err; 
     else { 
      if (!user) { 
       console.log('User does not exists!'); 
       response.json({ success: false, msg: 'User does not exists!' }); 
      } else { 
       userModel.comparePassword(password, user.password, (err, isMatch) => { 
        if (err) throw err; 
        else { 
         if (!isMatch) { 
          response.json({ success: false, msg: 'Password do not match!' }); 
         } else { 
          const token = jwt.sign(user, config.secret, { 
           expiresIn: 86400 // 1 day 
          }); 

          response.json({ 
           success: true, 
           token: "JWT " + token, 
           user: { 
            id: user._id, 
            name: user.name, 
            email: user.email, 
            role: user.role 
           } 
          }); 
         } 
        } 
       }); 
      } 
     } 
    }); 
}); 

passport.js

const JwtStrategy = require('passport-jwt').Strategy; 
const ExtractJwt = require('passport-jwt').ExtractJwt; 

const userModel = require('../models/usersModel'); 
const config = require('../config/database'); 

module.exports = function (passport) { 
    let opts = {}; 
    opts.jwtFromRequest = ExtractJwt.fromAuthHeader(); 
    opts.secretOrKey = config.secret; 

    passport.use(new JwtStrategy(opts, (jwt_payload, done) => { 

     userModel.getUserById(jwt_payload._doc._id, (err, user) => { 
      console.log(jwt_payload); 
      if (err) { 
       return done(err, false); 
      } 
      if (user) { 
       return done(null, user); 
      } else { 
       return done(null, false); 
      } 
     }); 
    })); 
} 

測試路線:

router.get('/profile', passport.authenticate('jwt', { session: false }), (request, response, next) => { 
    response.json({ user: request.user }); 
}); 

(PS:我試過console.log(jwt_payload);並沒有在控制檯中顯示。仍然在此請幫助。我是首發。 )

回答

0

當你得到你的jwt令牌後,你應該在每個請求中發送它。

header:authorization:JWT「token」

你在做嗎?

enter image description here

+0

是的。我在做 –

+0

您是否嘗試刪除過期以查看會發生什麼? –

+0

謝謝,你留給我吧。它現在有效。非常感謝你。 –