无redirect安全的护照login(Node.js)

我目前正在做一个Web应用程序,当用户login时,我不希望页面被redirect – 相反,我希望客户端只需更新当前页面(我想过使用AJAX请求)。 我正在使用带有护照的nodejs后端作为我的身份validation中间件。

客户端:

我目前有我想检查login状态的页面,只需调用一个函数onload:

function fetchLoginStatus(){ var request = new XMLHttpRequest(); request.open("GET", "/checkLogin.json", false); request.send(); } 

服务器端:

在服务器中,我有以下路线:

 app.get('/checkLogin.json', passport.authenticate('local-login'), function(req, res){ res.send(req.user.username); }); 

回到客户端,我检查这个响应数据,看看用户是否成功login。

这安全吗? 使用JSON进行身份validation? 有没有更好的方法来完成这个?

在代码中我看不到实际上将凭据信息发送到您的服务器。 假设“/checkLogin.json”不是JSON对象,而是http端点的名称,您必须使用POST请求的正文发送凭据信息(通常是用户和密码),如dylants所述。 例:

 //client side, angular.js: post with user, password $http({ method: 'POST', url: '/api/login', data: {usr: usr, psw:psw} }). success(function(data, status, headers, config) { $rootScope.authcode = self.ROLE_AUTH; $http.defaults.headers.common.Authorization = data.tkn; cb(null); }). error(function(data, status, headers, config) { console.log("error loggin in", data, status); cb("AUTHENTICATION_ERROR"); }); 

然后在服务器端,使用凭证信息来validation一些后端服务(通常是BD)并返回一个身份validation令牌:

 exports.login = function(request, reply){ var usr = request.payload.usr; var psw = request.payload.psw; var token = MuAuth.login(usr, psw, function(token){ if(token != null){ reply({tkn:token}); }else{ var error = Hapi.error.badRequest('auth error'); //return 401 if authorization fails error.output.statusCode = 401; error.reformat(); reply(error); } }); }; 

请注意,在客户端,如果authentication调用成功,authtoken被添加到http默认标题。 这样,它将被包含在所有将来的服务器调用中。