go - 解密 Gorilla session Cookie 数据

标签 go gorilla

首先,我要先说一下,我正在参加“夺旗”比赛,但我在解决与 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 值进行编码和解码的函数中使用 ssecurecookie package documentation提供了一个样板示例。

为了满足读取和修改已加密 cookie 的要求 - 在已加密的 securecookie 实例上使用 DecodeEncode 方法在上面的示例中进行设置。

类似的东西 ---

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/

相关文章:

go - 优雅地关闭 Gorilla 服务器

postgresql - 如何为 go-pg 中的每个查询动态设置表名?

javascript - Golang 和 JavaScript 模块

map - 无法从 map 分配给结构成员

go - 为什么这个程序中存在竞争条件?

go - 在gcp cloud函数中使用gorillamux

go - 在 net/http golang 中链接中间件

mongodb - 由于缺少 'ISODate',使用时间时 Golang + mgo 查询 mongodb 失败

go - 将字符串 slice 传递给可变参数空接口(interface)参数

go - 在go-plus atom中按项目添加gopath