Passport js fails to maintain session in cross-domain

前端 未结 3 1622
半阙折子戏
半阙折子戏 2020-12-08 08:39

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

相关标签:
3条回答
  • 2020-12-08 09:13

    As per Sriharsha's answer:

    • Set res.header("Access-Control-Allow-Credentials", "true");

    • Make sure you pass the credentials in the client side call. For example for AJAX, add this to your call: xhrFields: {withCredentials: true},

    Additionally:

    • Don't use the wildcard for Access-Control-Allow-Origin with a credentialed request

      As explained on MDN:

      when responding to a credentialed request, server must specify a domain, and cannot use wild carding


    I use this file, and call it from my main module with require("./enable-cors.js")(app);

    // enable-cors.js
    module.exports = function(app) {
    
        var methodOverride = require('method-override')
        app.use(methodOverride());
        var allowCrossDomain = 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', 'Content-Type, Authorization');
    
            // intercept OPTIONS method
            if ('OPTIONS' == req.method) {
                res.send(200);
            }
            else {
                next();
            }
        };
        app.use(allowCrossDomain);
        // Built upon: http://cuppster.com/2012/04/10/cors-middleware-for-node-js-and-express/#sthash.WdJmNaRA.dpuf
    
    };
    
    0 讨论(0)
  • 2020-12-08 09:16

    Allow the credentials to be shared by setting Access-Control-Allow-Credentials header. (I am not sure why you have commented in your code)

    res.header("Access-Control-Allow-Credentials", "true");
    

    then pass the credentials from javascript through XHR object.

    xhr.withCredentials = true;
    
    0 讨论(0)
  • 2020-12-08 09:26

    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!

    0 讨论(0)
提交回复
热议问题