2014-07-08 31 views
2

我目前正在制作一个Web应用程序,当用户登录时,我不希望将页面重定向 - 相反,我希望客户端只更新当前页面上(我想过使用AJAX请求)。我正在使用带护照的nodejs后端作为我的身份验证中间件。无重定向安全性的护照登录(Node.js)

客户方:

目前,我有,我要检查登录状态简单地调用一个函数的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); 
}); 

回到客户端上的,我检查这个响应数据,看是否有用户成功登录。

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

+1

使用API​​(JSON)进行身份验证非常正常,但通常这是通过“POST”请求而不是“GET”完成的。其中包含登录凭据(这意味着它确实应该是HTTPS)。这是你的意思吗? – dylants

回答

0

我在代码中看不到您实际上将凭证信息发送到您的服务器。假设“/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"); 
      }); 

然后,在服务器端,使用该凭证信息与一些后端服务(通常为BD)验证并返回认证令牌:

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); 
     } 
    }); 
}; 

注意的是,在客户端方面,如果认证调用成功,authtoken将被添加到http默认标题中。通过这种方式,它将被包含在所有未来对服务器的调用中。