簡體   English   中英

無重定向安全性的Passport登錄(Node.js)

[英]Passport Login without Redirect Security (Node.js)

我當前正在制作一個Web應用程序,在該應用程序中,當用戶登錄時,我不希望頁面被重定向-相反,我希望客戶端僅在其上更新當前頁面(我考慮過使用AJAX請求)。 我正在使用帶有護照的nodejs后端作為我的身份驗證中間件。

客戶端:

我目前有要檢查登錄狀態以僅調用函數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進行身份驗證? 有沒有更好的方法可以做到這一點?

我在您的代碼中看不到您實際上將憑證信息發送到服務器。 假設“ /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);
        }
    });
};

請注意,在客戶端,如果身份驗證調用成功,則將身份驗證令牌添加到http默認標頭中。 這樣,它將包含在以后所有對服務器的調用中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM