【问题标题】:Receiving and sending cookies with Go client?使用 Go 客户端接收和发送 cookie?
【发布时间】:2017-09-02 08:25:55
【问题描述】:

我希望我的 Go 应用程序通过网站进行身份验证,然后使用收到的 cookie 访问安全位置。以下 curl 示例准确地说明了我正在尝试做的事情:

通过x-www-form-urlencoded 对网站进行身份验证并保存 cookie。数据自动进行urlencoded:

curl 'https://www.example.com/login' \
    --cookie-jar cookies.txt \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --data 'user=USER NAME&pass=PASS'

现在身份验证 cookie 保存在 cookies.txt 中,我只是发送它以访问需要登录的页面:

curl 'https://www.example.com/profile' \
    --cookie cookies.txt

我不想将 cookie 存储在我的应用程序的磁盘上,只存储在内存中,以便我可以在需要时使用它。

有没有人举例说明如何在 Go 中实现这一点?

【问题讨论】:

标签: cookies web go http-authentication


【解决方案1】:

您会发现 Golang 的方法与 Java 中的方法非常相似。 确保您在登录处理程序中。 你只使用SetCoookie函数设置cookie

myCookie := http.Cookie{
    Name: "cookie Name",
    Value: "cookieValue",
  }

  http.SetCookie(w, &myCookie)

出于安全原因,建议将 httpOnly 标志添加到您的 cookie。

httpOnly: true

此标志为 true 与 HTTPS/HTTP 无关。 它仅意味着不允许脚本,仅 HTTP 请求,以防止跨站点脚本 (XSS) 攻击。 您从客户端存储 cookie,然后在需要时调用 cookie 并验证它是否是正确的 cookie 以及您将其发送到的正确客户端。 这种方法可以使用:

cookie, err := r.Cookie("appointment")
checkErr(err)

现在你解密 cookie。验证它。随心所欲地做你想做的事。 然后将您的回复返回给客户,无论它是否是正确的客户。 希望这有点帮助

【讨论】:

    【解决方案2】:

    对于 golang,您可以 Add a cookie 发送请求,您还可以在发出 Web 请求后使用 this 函数获取 cookie。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-16
      • 1970-01-01
      • 2019-08-25
      • 2021-12-04
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 2018-04-16
      相关资源
      最近更新 更多