Passport js从跨域登录



用户如何从另一个域登录。示例:主站点有登录表单,ajax发布到我的nodejs服务器上的一个路由。

// submit form to node server(app) FROM WEBSITE
$('#submit-project-form').submit(function(e){
    e.preventDefault();
    var formData = $(this).serialize();
    $.ajax({
        url: "http://localhost:3100/login",
        data: formData,
        type: "POST",
        crossDomain: true,
        dataType: "json",
        success: function(response){
            console.log(response.responseText);
        },
        error: function(response) {
            var success =  $($.parseHTML(response.responseText)).filter("body"); 
            console.log(response.responseText);
        }
     }); 
});
// Passport POST auth methods. Listen to POST route from website
app.post('/login', passport.authenticate('local-login', {
    successRedirect : '/', // re-run user.index which should pass as a user and render profile
    failureRedirect : '/login', // redirect back to the signup page if there is an error
    failureFlash : true
}));

这触发了路线,我得到了登录护照策略所需的电子邮件和密码。

passport.use('local-login', new LocalStrategy({
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
    console.log(req.body.email); // returns email entered in cross-domain field
    console.log(email); // returns email entered in cross-domain field
    // find a user whose email is the same as the forms email
    // we are checking to see if the user trying to login already exists
    AppUser.findOne({ 'local.email' :  email }, function(err, user) {
        // if there are any errors, return the error before anything else
        if (err)
            return done(err);
        // if no user is found, return the message
        if (!user)
            return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
        // if the user is found but the password is wrong
        if (!user.validPassword(password))
            return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
        // all is well, return successful user
        return done(null, user); 
    });
}));

CORS在nodejs服务器上启用,它之所以有效,是因为我可以跨域提交支付,并且我会从服务器得到响应。

我认为问题是护照有successRedirect,问题出在哪里,我可能需要一个自定义的成功功能?有什么想法吗?

似乎添加到ajax中的xhrFields使其工作。我将继续测试,但我能够使用跨域POST登录,非常酷。

xhrFields: {
  withCredentials: true
},

相关内容

  • 没有找到相关文章

最新更新