护照js无法在跨域中维护会话 [英] Passport js fails to maintain session in cross-domain

查看:133
本文介绍了护照js无法在跨域中维护会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用护照JS,express和mongoose制作一个API。当我在同一个域中测试它维护会话和工作正常。但在跨域中它失败。任何线索如何可以使用相同的配置在跨域中维护会话。以下是代码

I am using passport JS, express and mongoose to make an API. When I test it in same domain it maintain session and works fine. But in cross domain it fails. Any clue how can i maintain the session in cross domain using the same configuration. Following is the code

 allowCrossDomain = function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    res.header("Access-Control-Allow-Headers", req.headers["access-control-request-headers"]);
    // res.header("Access-Control-Allow-Credentials", "true");
    if ("OPTIONS" == req.method) {
        res.send(200);
    } else {
        next();
    }

  //allow all crossDomain request
app.use(allowCrossDomain);

//session handling
app.use(express.cookieParser("gallery"));
app.use(express.session());
app.use(passport.initialize());
app.use(passport.session());

app.use(function(req, res, next) {
    // check if client sent cookie
    var cookie = req.cookies.cokkieName;
    if (cookie === undefined) {
        //set up cookie here by a random number
        });
    }
    next(); // <-- important!
});
passport.use(new LocalStrategy({
    usernameField: "email"
},
function(email, password, done) {
    User.authenticate(email, password, function(err, reply) {
       //authenticate user and call the callback
            return done(err, false);

    });
}));


passport.serializeUser(function(user, done) {
return done(null, user._id);
});


passport.deserializeUser(function(id, done) {
//find user via id and return the user details
return done(null, user._id);
});

   app.post("/login", function(req, res, next) {
    passport.authenticate("local",
        function(err, data, info) {
            //custom callback
            user.getProfile(req, res, next, err, data, info);
        })(req, res, next);
});


推荐答案

在快速应用中配置任何内容之前,请使用以下(完全相同)为跨网域设置响应标头:

I was having the same problem. Before configuring anything in express app, use the following(exactly the same) to set header of response for cross-domain :

app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
if ('OPTIONS' == req.method) {
     res.send(200);
 } else {
     next();
 }
});

它适用于我。祝你好运!

It works for me. Best of luck!

这篇关于护照js无法在跨域中维护会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆