jul*_*sti 5 rest node.js angularjs restify passport.js
我有一个 NodeJs REST 服务,我们称之为 -后端的NodeRest和前端的 AngularJs。
NodeRest应该与移动应用程序以及 Web 应用程序一起使用,在我的情况下它是 AngularJs 应用程序。
NodeRest 的架构在使用 PassportJs 时应该解决以下问题:
服务器不应将用户重定向到 Facebook 以在何时进行授权
app.get('/auth/facebook', passport.authenticate('facebook'));
Run Code Online (Sandbox Code Playgroud)
已被调用。
如果它要重定向它,客户端将不会得到任何东西,因为回调 url 链接到NodeRest httpL//noderest/facebook/callback。相反,它应该提供重定向 uri,以便我可以将其发送回客户端(angularJs、mobile 等...)。像这样:
app.get('/auth/facebook', passport.authenticate('facebook', function(redirectUri){
//emit socket event to the client with redirect uri as a response data. }));
Run Code Online (Sandbox Code Playgroud)
我决定在授权过程中使用 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);
});
Run Code Online (Sandbox Code Playgroud)
客户端将负责重定向到 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 });
});
Run Code Online (Sandbox Code Playgroud)
所有这些东西背后的总体思路是从不同类型的客户端应用程序(移动、网络、桌面等)获得授权。客户端必须只能将重定向 uri 重定向到 oauth2 提供商(facebook、twitter 等)并自行重定向到该 uri。该NodeRest约需进一步措施护理(即处理的回调,并通知客户端)。
我不知道这是否是我正在研究的一个很好的解决方案,因此任何类型的反馈都会非常有帮助。我将不胜感激任何形式的反馈。
提前谢谢你,朱利安
Passport 在这个问题上的记录很少——我也为此苦苦挣扎了很长一段时间。我发现你可以调用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);
};
Run Code Online (Sandbox Code Playgroud)
这是为本地身份验证设置的,但我相信它应该可以与 facebook 身份验证一起使用,无需任何更改。