【问题标题】:How create cookies in browser with node js如何使用 node js 在浏览器中创建 cookie
【发布时间】:2020-10-14 01:28:39
【问题描述】:

我在node js中有一个用户身份验证功能,我没有使用身份验证,护照或其他lib,我不太了解,所以我做了自己的身份验证功能。 但是,我的功能仅对用户是真实的,它不会创建 cookie,我需要在“到期日期”节点上创建 cookie,并且一旦等待,它就会将我重定向回登录路线。我想在这个函数中实现这个:

function verify(req,res,username,password){                   
 db.serialize(function (){                                      
 const query = 'SELECT * from Users WHERE User = (?) AND Password = (?)'
 db.all(query,[username, password],function(err,rows){
 if(err) {
  console.log(err);
 }
 if(rows.length == 1){
  console.log(rows);                                            
  console.log("Correct user");
  res.render(__dirname + "/View/Home/index.handlebars");
 }                                                             
 else{
  console.log("Incorrecto user!")
  res.redirect('/login')
 }
});
});
}

这是我在节点 js 中的路由

app.get("/login", (req,res) => {                               
 res.render(__dirname + "/View/Home/login.handlebars");       
});

app.post("/",(req,res) => {                                    
 const username = req.body.username                          
 const password = req.body.password
 verify(req,res,username,password)

});

如果用户有效,我需要在 verify() 函数中创建一个 cookie,当 cookie 过期时,用户会再次重定向到“/login”路由

【问题讨论】:

    标签: javascript node.js sqlite session cookies


    【解决方案1】:

    假设您使用的是 Express 服务器,您可以使用 res.cookie(name, value, options) 设置 cookie。 options 是一个对象,maxAge 属性可能是你想要的,它是一个数字,它是在它过期之前的毫秒数。例如,如果用户有效,您可以使用res.cookie('username', username, {maxAge: 172800000 /* two days */})

    您可以使用req.cookies 访问请求的cookie,它是cookie 名称键和字符串值的对象。您可以检查'username' 键是否存在且有效,如果不存在,则使用res.redirect 进行重定向。

    function verify(req,res,username,password){
     // Place this block wherever you want it to check for a valid cookie
     // Depending on the context when this function is called, that might not be at the start
     if(typeof(req.cookies.username) != 'string')
       res.redirect('/login');     
    
     db.serialize(function (){                                      
     const query = 'SELECT * from Users WHERE User = (?) AND Password = (?)'
     db.all(query,[username, password],function(err,rows){
     if(err) {
      console.log(err);
     }
     if(rows.length == 1){
      console.log(rows);                                            
      console.log("Correct user");
      // Set Cookie
      res.cookie('username', username, {maxAge: 172800000 /* two days */});
      res.render(__dirname + "/View/Home/index.handlebars");
     }                                                             
     else{
      console.log("Incorrecto user!")
      res.redirect('/login')
     }
    });
    });
    }
    

    【讨论】:

    • 是的,我正在使用 express,你能给我一个我的代码示例吗,因为我之前使用过 cookie,但我认为我没有以正确的方式进行操作,因为它不起作用,它没有'不再出错,就像我没有创建 cookie。
    • @Jessica 已编辑。
    • 我有以下错误:发送到客户端后无法设置标头
    • 我相信你的代码是我需要的,但我需要每隔几秒检查一次 cookie 是否存在。
    【解决方案2】:

    使用 Keycloak

    下载 Offical Keycloak Download Page

    为 Linux/Unix 安装

    ./bin/standalone.sh
    

    ** 为 Windows 安装**

    \bin\standalone.bat
    

    像这样使用arg -b 绑定网络地址(默认为127.0.0.1)

    ./bin/standalone.sh -b 192.168.1.150
    

    安装 Keycloak-nodejs-connect

    npm install keycloak-connect
    

    Official Node.js Example from Github

    参考:Getting Started Guide

    【讨论】:

    • 我总共花了大约 8 个小时阅读文档,我无法在代码中使用护照,因为我使用的是 sqlite,我找到了一个代码,但它不是我需要的,最后,我找不到我需要的东西,也无法摆脱困境。所以我做了这个功能,因为经过 100 万次尝试后,我不得不用另一种方式来做。 :(
    • @Jessica 你是对的!护照文件没那么有用,遗漏了很多东西。老实说,我改用 Kaycloak。非常友好的用户界面,后端和前端也是如此!深度控制,除了您的应用程序之外的所有内容。您可以拥有 3rd 方身份提供商 Google、Github、Twitter...等您会印象深刻的是,使用 Keycloak 和 Node.js 可以轻松地进行操作,您只需执行 app.get('/login', keycloak.protect(), function (req, res) { 并且如果他/她/它没有经过身份验证的用户必须重定向借助令牌、cookie 和第三方(如数十个 dem)到您的单点登录服务器
    • 它拥有你所需要的一切,从认证、授权到被认证 =) 快乐冲浪!
    • 注册用户的登录是在sqlite中的,我搜了一下,没找到这个库里的很多内容:(
    • 身份验证在我的脑海中已经成为一件非常复杂的事情,哈哈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 2013-11-02
    • 1970-01-01
    • 2020-11-01
    • 2020-02-07
    • 2018-03-13
    相关资源
    最近更新 更多