首先,我要先说一下,我正在参加“夺旗”比赛,但我在解决与 Go Gorilla session 相关的问题时遇到了一些困难。我从来没有用 Go 编写过代码,所以这很有趣,但也很令人沮丧:)
我有一把 secret key 。我有一个编码的 Cookie。我需要使用我拥有的 key 来解码 cookie,编辑其中的任何数据,并使用我更改的数据重新加密,以在挑战中取得进展。
我已阅读 Gorilla Sessions Package 文档,但没有真正得到任何帮助。
任何人都可以帮忙吗?我从哪里开始?
最佳答案
查看文档 - gorilla 提供了 secure cookie package 。 根据您的应用程序架构 - 基本实现可以按如下方式工作:
创建一个供您的应用程序使用的 session 管理包。为了举例 - 让我们称之为 sessionmngr
在sessionmngr
内部,导入“github.com/gorilla/securecookie”
。
在 sessionmngr
包中,使用小写的 init()
函数来设置 securecookie
的私有(private)实例。导入包后,小写的 init() 函数将按照声明的顺序调用。 (查看语言 spec 了解更多信息)。您将使用此实例对标准库的 http.Request
中的 cookie 进行编码和解码。
import (
"github.com/gorilla/securecookie"
//you will need this later
"http"
)
//declare private secure cookie
var s *securecookie.SecureCookie
//initialize it here (taken from the gorilla docs example)
func init() {
var hashKey = []byte("very-secret")
var blockKey = []byte("a-lot-secret")
s = securecookie.New(hashKey, blockKey)
}
然后,您将在整个包中需要对 cookie 值进行编码和解码的函数中使用 s
。 securecookie package documentation提供了一个样板示例。
为了满足读取和修改已加密 cookie 的要求 - 在已加密的 securecookie
实例上使用 Decode
和 Encode
方法在上面的示例中进行设置。
类似的东西 ---
func DecodeAndModify(w http.ResponseWriter, r *http.Request) {
//get reference to cookie if set
if cookie, err := r.Cookie("cookie-name"); err == nil {
value := make(map[string]string)
//use Decode to get the value from the cookie
if err = s.Decode("cookie-name", cookie.Value, &value); err == nil {
//modify the value in some way
value["newKey"] = "newValue"
//re-encode it
if encoded, err := s.Encode("cookie-name", value); err == nil {
cookie := &http.Cookie{
Name: "cookie-name",
Value: encoded,
Path: "/",
}
http.SetCookie(w, cookie)
}
}
}
}
关于go - 解密 Gorilla session Cookie 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39690846/