简体   繁体   English

使用 Go 客户端接收和发送 cookie?

[英]Receiving and sending cookies with Go client?

I want my Go application to authenticate with a website and then use the received cookie to access secure locations.我希望我的 Go 应用程序通过网站进行身份验证,然后使用收到的 cookie 访问安全位置。 The following curl examples illustrates exactly what I'm trying to do:以下 curl 示例正好说明了我正在尝试做的事情:

Authenticate with website via x-www-form-urlencoded and save cookie.通过x-www-form-urlencoded与网站进行身份验证并保存 cookie。 Data is urlencoded automatically:数据自动进行 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'

Now authentication cookie is saved in cookies.txt and I just send that to access a page that requires login:现在身份验证 cookie 保存在cookies.txt ,我只是发送它来访问需要登录的页面:

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

I don't want to store the cookie on disk in my application, only in memory so I can use it when required.我不想将 cookie 存储在我的应用程序的磁盘上,只存储在内存中,这样我就可以在需要时使用它。

Does anyone have an example of how this can be achieved in Go?有没有人有一个如何在 Go 中实现这一目标的例子?

对于 golang,您可以向请求添加 cookie ,您也可以在发出 Web 请求后使用功能获取 cookie。

you will find that Golang's approach is much similar to the one in Java.您会发现 Golang 的方法与 Java 中的方法非常相似。 make sure you are inside your login handler.确保您在登录处理程序中。 you only set the cookie using the SetCoookie function您只使用SetCoookie函数设置 cookie

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

  http.SetCookie(w, &myCookie)

it is recommended for security reasons to add the httpOnly flag to your cookie.出于安全原因,建议将 httpOnly 标志添加到您的 cookie。

httpOnly: true

this flag true has nothing to do with HTTPS/HTTP.这个标志 true 与 HTTPS/HTTP 无关。 it only means no scripts allowed, HTTP requests only, to prevent Cross-site scripting (XSS) attacks.它仅表示不允许使用脚本,仅允许使用 HTTP 请求,以防止跨站点脚本 (XSS) 攻击。 you store the cookie from the client-side, then when required you call the cookie and you verify if it the right cookie and the right client u send it to.您从客户端存储 cookie,然后在需要时调用 cookie 并验证它是否是正确的 cookie 以及您将其发送给正确的客户端。 this approach can be done using:这种方法可以使用:

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

now u decrypt the cookie.现在你解密cookie。 verify it.验证一下。 do whatever the hell u want with it.随心所欲地用它做任何事。 then return your response to the client if it is the right client or not.然后将您的响应返回给客户端,如果它是正确的客户端。 hope this kinda helps希望这有点帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM