5

我有一个 NodeJs REST 服务,我们称之为 - NodeRest在我的后端,AngularJs 在我的前端。

NodeRest应该与移动应用程序以及网络应用程序一起使用,在我的情况下它是 AngularJs 应用程序。

NodeRest 的架构在使用 PassportJs 时应该解决以下问题:

服务器不应将用户重定向到 facebook 以授权何时

app.get('/auth/facebook', passport.authenticate('facebook'));

已被调用。

如果它要重定向它,客户端将不会得到任何东西,因为回调 url 链接到NodeRest httpL//noderest/facebook/callback。相反,它应该提供重定向 uri,因此我可以将其发送回客户端(angularJs、移动设备等)。像这样:

app.get('/auth/facebook', passport.authenticate('facebook', function(redirectUri){ 
//emit socket event to the client with redirect uri as a response data. })); 

我决定在授权过程中使用 socket.io 作为通信通道。

客户:

var socket = io.connect(baseUrl);
    socket.on('auth:facebook:callback:getCalled', function (data) {
      // callback get called on server side.
      // user has been authenicated.
      // so now, user can talk with our NodeRest server to get and post data.      
      var firstName = data.firstName;
      var lastName = data.lastName;
});

$http.get(baseUrl + '/login/facebook').success(function(data, status, headers, config){
      redirectUriToAuthenticate = data;      
      $location.path(data);
});

客户端将负责重定向到 facebook/twitter 等,以获得用户授权。之后,用户将被重定向到回调 url。

服务器:

app.get('/auth/facebook/callback', function(){
  passport.authenticate('facebook', { successRedirect: '/', failureRedirect: '/login' })
  //socket.io emit event to the client with user data.
  io.sockets.on('connection', function (socket) {
  socket.emit('auth:facebook:callback:getCalled', { data: User });
});

所有这些东西背后的一般想法是从不同类型的客户端应用程序(移动、Web、桌面等)获得授权。客户端必须只能将 uri 重定向到 oauth2 提供者(facebook、twitter 等)并自行重定向到该 uri。NodeRest将负责进一步的步骤(即处理回调和通知客户端)

我不知道这是否是我正在研究的一个好的解决方案,所以任何类型的反馈都会很有帮助。我将不胜感激任何形式的反馈。

提前谢谢你,朱利安

4

1 回答 1

1

护照在这个问题上的记录很差——我也为此苦苦挣扎了很长时间。我发现你可以调用 passport.authenticate(type, fn)(req, res, next),并且在 fn 中,你可以区分可以登录的用户和不能登录的用户。不过,由您决定是否调用 req.logIn。

仅供参考,我假设您正在使用会话:

module.exports.createSession = function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) {
      res.json(500, {ok: false});
    } else if(!user) {
      // you would probably want to do more work here
      // for example distinguishing between bad login credentials,
      // canceling, users not ready to log in (pending), etc.
      res.json(401, {ok: false});
    } else {
      req.logIn(user, function(err) {
        if (err) {
          res.json(500,{ok: false});
        } else {
          res.json(200, {
            ok:req.isAuthenticated(),
            username: req.user.username,
            email: req.user.email
          });
        }
      });
    }
  })(req, res, next);
};

这是为本地身份验证设置的,但我相信它应该与 facebook auth 一起使用而无需任何更改。

于 2014-04-09T02:24:59.020 回答