简体   繁体   中英

Passport Login without Redirect Security (Node.js)

I am currently making a web application where when the user logs in, I don't want the page to be redirected -- instead, I want the client to simply update the current page its on (I thought about using AJAX requests). I am using a nodejs backend with passport as my authentication middlewear.

CLIENTSIDE:

I currently have the page that i want to check login status to simply call a function onload:

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

SERVERSIDE:

In the server, i have the following route:

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

Back on the Client Side, I check this response data to see if a user has successfully logged in.

Is this safe? Using JSON to authenticate? And is there a better way to accomplish this?

I can't see in your code that you actually send credential information to your server. assuming that "/checkLogin.json" is not a JSON object but the name of the http endpoint, you must send credentials information (usually, user and password) using the body of a POST request, as dylants says. example:

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

then, in the server side, you use the credential information to validate with some backend service (usually a BD) and returns an authentication token:

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

Notice that in the client side, if the authentication call is successful, the authtoken is added to the http default headers. in this way, it will be included in all future calls to the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM