nodejs:会话ID在重定向后正在更改。如何保持用户会话数据的持久性?

时间:2019-04-24 08:46:09

标签: node.js express redirect cookies express-session

曾见过许多类似的问题,但不知道如何解决。 我有一台使用Cookie会话的快递服务器。服务器正在调用google auth api。

因为它是一个用于多用户的应用程序,所以我必须将google auth信息与用户会话相关联

从Google取回它们后,我将这些身份验证数据保存在会话中。 数据保存在会话中。这里没问题

但是在重定向到另一个快速路由后,会话有所不同,因此无法访问已保存的数据。

这是代码

思考

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main()
        {
            Example1();
            Example2();
            Thread.Sleep(500);
            Console.WriteLine("Main");
        }

        public static void Example1()
        {
            try
            {
                Console.WriteLine("Example1");
                Task t = Task.Run(() => Foo());
                t.Wait();
            }
            catch (AggregateException e)
            {
                foreach (var ex in e.InnerExceptions)
                    Console.WriteLine(ex.Message);
            }
        }

        public static void Example2()
        {
            try
            {
                Console.WriteLine("Example2");
                Task<string> t = Task.Run(() => { Foo(); return "Task result"; });
                string result = t.Result;
                Console.Write(result);
            }
            catch (AggregateException e)
            {
                foreach (var ex in e.InnerExceptions)
                    Console.WriteLine(ex.Message);
            }
        }

        public static void Foo()
        {
            throw new Exception("Blahh Exception");
        }
    }
}

4 个答案:

答案 0 :(得分:0)

npm install --save cors

允许通过cors中间件访问适当的端口访问

app.use (cors ({
         credentials: true,
         origin: [
                 "http: // your domain address",
                 "http: // yourdomain address: port"
                 ]
}));

尝试通过“保存”功能的回调进行重定向。

req.session.save ((err) => {
// try to redirect within callback function
res.redirect ("/googleauth/test");
})

如果采用post方法,请按如下所示替换它。

res.redirect (307, "/googleauth/test");

然后在客户端代码中的数据传输模块(例如axios等)的配置中设置withCredentials:true。

const config = {
      headers: {'Content-Type': 'application/json'},
      withCredentials:true
      };

axios.post('http://your domain address:port/route',{},config)
   .then( response => {
   //response.data your codes
});

答案 1 :(得分:0)

我也遇到您的问题,我尝试过对sameSite进行“松懈”操作,

app.use(
  session({
    name: SESSION_NAME,
    secret: SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
      maxAge: parseInt(SESSION_LIFETIME, 10), // 24H in config file
      httpOnly: true,
      sameSite: "lax",
      secure: !IN_DEV
    }
  })
);

但我认为sameSite相等的“严格”对更好的安全性是必要的 大家有什么解决办法吗?谢谢

答案 2 :(得分:0)

在本地运行res.redirect时,我遇到了同样的问题,会话ID更改了,我无法检索保存的会话数据。我花了很多时间研究这个问题,尝试了上述所有答案,包括明确运行req.session.save()。对我来说固定的是我意识到自己 当我的原始页面位于http://127.0.0.1:3000/path上时,重定向到http://localhost:3000/path

Express显然将它们视为单独的域,因此,即使它们似乎指向同一页面,我也在重定向时获得了新的会话ID。

答案 3 :(得分:0)

前一段时间我遇到了同样的问题。我仅通过从save方法获得回调后才继续进行操作来解决该问题。看起来很傻,但是可以为我工作。

req.session.save((err) => {
    if (err) {
        return res.send("err while saving session information");
    }
    console.log(req.session.oauth2Client);
    return res.redirect("/googleauth/test");
});

return new Promise((resolve, reject) => {
    req.session.save((err) => {
        if (err) {
            reject(err);
        }
        resolve(res.redirect("/googleauth/test"));
    });
});

让我知道它是否对您有用。
参考:https://github.com/expressjs/session/issues/660

相关问题