您可以使用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