2017-08-28 158 views
2

我試圖設置我的節點JS API。節點JS身份驗證與護照-Jwt未經授權

我有一個用戶模式:

// Dependencies 
var restful = require('node-restful'); 
var mongoose = restful.mongoose; 

var bcrypt = require('bcrypt'); 

// Schema 
var userSchema = new mongoose.Schema({ 
    username: { 
     type: String, 
     required: true, 
     unique: true}, 
    firstname: { 
     type: String, 
     required: true 
    }, 
    lastname: { 
     type: String, 
     required: true 
    }, 
    email: { 
     type: String, 
     required: true, 
     unique: true, 
     lowercase: true 
    }, 
    password: { 
     type: String, 
     required: true}, 
}, 
{ 
    timestamps: true 
}); 

// Saves the user's password hashed 
userSchema.pre('save', function (next) { 
    var user = this; 
    if (this.isModified('password') || this.isNew) { 
    bcrypt.genSalt(10, function (err, salt) { 
     if (err) { 
     return next(err); 
     } 
     bcrypt.hash(user.password, salt, function(err, hash) { 
     if (err) { 
      return next(err); 
     } 
     user.password = hash; 
     next(); 
     }); 
    }); 
    } else { 
    return next(); 
    } 
}); 


// Use bcrypt to compare passwords 
userSchema.methods.comparePassword = function(pw, cb) { 
    bcrypt.compare(pw, this.password, function(err, isMatch) { 
    if (err) { 
     return cb(err); 
    } 
    cb(null, isMatch); 
    }); 
}; 

module.exports = restful.model('Users', userSchema); 

我想使用的護照與智威湯遜認證:

// Dependencies 
var JwtStrategy = require('passport-jwt').Strategy; 
var ExtractJwt = require('passport-jwt').ExtractJwt; 
var config = require('../config/database'); 

// Load models 
var User = require('../models/user'); 

// Logique d'authentification JWT 
module.exports = function(passport) { 
    var opts = {}; 
    opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('JWT'); 
    opts.secretOrKey = config.secret; 
    opts.audience = 'localhost'; 

    passport.use(new JwtStrategy(opts, function(jwt_payload, done) { 
    User.findById(jwt_payload._id, function(err, user) { 
     if (err) { 
     return done(err, false); 
     } 
     if (user) { 
     done(null, user); 
     } else { 
     done(null, false); 
     } 
    }); 
    })); 
    passport.use(new JwtStrategy(opts, function(jwt_payload, done) { 
    Company.findById(jwt_payload._id, function(err, company) { 
     if (err) { 
     return done(err, false); 
     } 
     if (company) { 
     done(null, company); 
     } else { 
     done(null, false) 
     } 
    }); 
    })); 
}; 

我的認證路線:

// User 
router.post('/users/login', (req, res) => { 
    User.findOne({ 
     email: req.body.email 
    }, (err, user) => { 
     if (err) throw err; 

     if (!user) { 
      res.json({success: false, message: 'Authentication failed. User not found.'}); 
     } else { 
      // Check if passwords matches 
      user.comparePassword(req.body.password, (err, isMatch) => { 
       if (isMatch && !err) { 
        // Create token if the password matched and no error was thrown 
        var token = jwt.sign(user, config.secret, { 
         expiresIn: 10080 // in seconds 
         }); 
        res.json({success: true, token: 'JWT ' + token, user: { 
         id: user._id, 
         username: user.username, 
         email: user.email 
        }});  
       } else { 
        res.json({success: false, message: 'Authentication failed. Passwords did not match.'}); 
       } 
      }); 
     } 
    }); 
}); 

一切工作的偉大郵遞員。 令牌已正確生成並使用用戶信息進行簽名。

但是我有一個受保護的航線上驗證了一個問題:

router.get('/users/profile', passport.authenticate('jwt', { session: false }), function(req, res) { 
    res.send('It worked! User id is: ' + req.user._id + '.'); 
    }); 

每次,它給了我一個「未經授權401」錯誤。

我真的不知道哪裏出了問題,我認爲這個問題是各地jwtFromRequest,我也試圖與承載,但它也不起作用......

+0

你具有相同的名稱,公司和用戶2分的策略,也許這弄亂了護照?我會假設它在你期待第一個時使用第二個策略 –

回答