【问题标题】:How to access HTTP Cookie in Node.JS - JWT如何在 Node.JS 中访问 HTTP Cookie - JWT
【发布时间】:2021-02-17 08:50:54
【问题描述】:

这似乎是一个多余的问题,但请先听我说完:

我正在使用 React 前端和节点后端。我正在使用 JWT 来处理用户身份验证。现在,我在实际使用 JWT 和执行身份验证时遇到了麻烦。这就是我卡住的地方:

~ 我尝试在后端将令牌设置为 http cookie。如果我与邮递员一起工作,我会看到正在设置令牌。但是,当我使用 req.cookies.token 尝试接收令牌 cookie 以在后端执行验证时,我得到一个未定义的值。我应该以某种方式将 cookie 从前端发送到后端吗?我觉得这是我缺少的部分。

请指教!

【问题讨论】:

    标签: node.js reactjs cookies jwt jwt-auth


    【解决方案1】:

    所以我可以为您提供一个使用 express-sessionconnect-mongodb-session 来处理会话的替代解决方案,这往往是流行且有些安全的服务器会话处理解决方案

    首先你需要以下包

    npm i express-session connect-mongodb-session 或 yarn add express-session connect-mongodb-session

    现在我们有了需要设置 mongoStore 和 express-session 中间件的包:

    //Code in server.js/index.js (Depending on your server entry point)
    import expressSession from "express-session";
    import MongoDBStore from "connect-mongodb-session";
    import cors from "cors";
    const mongoStore = MongoDBStore(expressSession);
    
    const store = new mongoStore({
      collection: "userSessions",
      uri: process.env.mongoURI,
      expires: 1000,
    });
    app.use(
      expressSession({
        name: "SESS_NAME",
        secret: "SESS_SECRET",
        store: store,
        saveUninitialized: false,
        resave: false,
        cookie: {
          sameSite: false,
          secure: process.env.NODE_ENV === "production",
          maxAge: 1000,
          httpOnly: true,
        },
      })
    );
    

    现在会话中间件已准备就绪,但现在您必须设置 cors 以接受您的 ReactApp,以便传递 cookie 并由服务器将其设置在那里

    //Still you index.js/server.js (Server entry point)
    
    app.use(
      cors({
        origin: "http://localhost:3000",
        methods: ["POST", "PUT", "GET", "OPTIONS", "HEAD"],
        credentials: true,
      })
    );
    

    现在我们的中间件都设置好了,让我们看看你的登录路径

    router.post('/api/login', (req, res)=>{
        //Do all your logic and now below is how you would send down the cooki
    
        //Note that "user" is the retrieved user when you were validating in logic
        // So now you want to add user info to cookie so to validate in future
        const sessionUser = {
           id: user._id,
           username: user.username,
           email: user.email,
        };
        //Saving the info req session and this will automatically save in your     mongoDB as configured up in sever.js(Server entry point)
        request.session.user = sessionUser;
    
        //Now we send down the session cookie to client
        response.send(request.session.sessionID);
    
    })
    

    现在我们的服务器已准备就绪,但现在我们必须修复在客户端发出请求的方式,以便此流程可以 100% 工作:

    以下代码:处理登录的 React 应用程序

    //So you will have all your form logic and validation and below
    //You will have a function that will send request to server 
    
    const login = () => {
        const data = new FormData();
        data.append("username", username);
        data.append("password", password);
    
        axios.post("http://localhost:5000/api/user-login", data, {
          withCredentials: true, // Now this is was the missing piece in the client side 
        });
    };
    

    现在有了所有这些,您现在拥有作为 httpOnly 的服务器会话 cookie

    【讨论】:

      猜你喜欢
      • 2016-05-19
      • 2017-01-02
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      • 2021-07-25
      相关资源
      最近更新 更多