1

我已经在线阅读了整整一天,并发现所有的解决方案都是局部的而不是重点。我有一个API写在节点和表达 - (/ api/plans /)和(api/users /)。目前,我已经能够实现简单的电子邮件和密码注册和登录功能。如果用户成功登录,我会在节点服务器上生成一个令牌并将其发回到Angular Front端。但是我的API可以在没有任何身份验证的情况下访问,我想改变它。平均堆栈 - 我如何允许API访问仅限登录(电子邮件/密码和Facebook登录)用户

我想限制只有我登录的前端(Angular)用户才能访问API。此外,除了提供简单的电子邮件和密码注册外,用户还可以注册/登录,也想给Facebook一个单一的标志。

我想用护照Facebook的策略,这会给我的Facebook的访问令牌,但我失去了对如何我可以用电子邮件/密码令牌我现在再怎么样我产生正确的Facebook访问令牌整合我可以使用这些标记来保护我的API端点只能登录用户。

寻找建议,关于如何最好地去做。

回答

2

您可以使用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时验证用户是否登录。

+0

谢谢,伙计。智威汤逊是要走的路。 – manutdfan

+0

如果您认为这对您是正确的,请接受答案。 – leobelizquierdo

相关问题