您可以使用jsonwebtoken來保護您的api。製作一條匹配所有請求的路線到您的api app.use('/api', apiRoutes);
。然後,在這個文件中做這樣的事情:
var express = require('express');
var route = express.Router();
var jwt = require('jsonwebtoken');
route.post('/authenticate', function(req, res) {
// here check if the user is log in (use params from the 'req' object)
// and generate a token with jwt
// find the user
User.findOne({
username: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.json({ success: false, message: 'Authentication failed. User not found.' });
} else {
// check if password matches
if (user.password != req.body.password) {
res.json({ success: false, message: 'Authentication failed. Wrong password.' });
} else {
// if user is found and password is right
// create a token
var token = jwt.sign(user, process.env.superSecret, {
expiresInMinutes: 1440 // expires in 24 hours
});
// return the information including token as JSON
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
}
});
}
// TODO: route middleware to verify a token
route.use(function(req, res, next) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, process.env.superSecret, function(err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
// route to show a random message (GET http://localhost:3000/api/)
route.get('/', function(req, res) {
res.json({ message: 'Welcome to the coolest API on earth!' });
});
module.exports = route;
您可以使用護照,Facebook的戰略或不加區分自己的本地策略。您所需要的只是一種機制,以便在用戶嘗試訪問api時驗證用戶是否登錄。
謝謝,夥計。智威湯遜是要走的路。 – manutdfan
如果您認爲這對您是正確的,請接受答案。 – leobelizquierdo