Gogorillasecurecookie库的安装使用详解
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《Gogorillasecurecookie库的安装使用详解》,聊聊库、gorilla、securecookie,希望可以帮助到正在努力赚钱的你。
简介
cookie 是用于在 Web 客户端(一般是浏览器)和服务器之间传输少量数据的一种机制。由服务器生成,发送到客户端保存,客户端后续的每次请求都会将 cookie 带上。cookie 现在已经被多多少少地滥用了。很多公司使用 cookie 来收集用户信息、投放广告等。
cookie 有两大缺点:
- 每次请求都需要传输,故不能用来存放大量数据;
- 安全性较低,通过浏览器工具,很容易看到由网站服务器设置的 cookie。
gorilla/securecookie提供了一种安全的 cookie,通过在服务端给 cookie 加密,让其内容不可读,也不可伪造。当然,敏感信息还是强烈建议不要放在 cookie 中。
快速使用
本文代码使用 Go Modules。
创建目录并初始化:
$ mkdir gorilla/securecookie && cd gorilla/securecookie $ go mod init github.com/darjun/go-daily-lib/gorilla/securecookie
安装gorilla/securecookie库:
$ go get github.com/gorilla/securecookie
package main
import (
"fmt"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"log"
"net/http"
)
type User struct {
Name string
Age int
}
var (
hashKey = securecookie.GenerateRandomKey(16)
blockKey = securecookie.GenerateRandomKey(16)
s = securecookie.New(hashKey, blockKey)
)
func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
u := &User {
Name: "dj",
Age: 18,
}
if encoded, err := s.Encode("user", u); err == nil {
cookie := &http.Cookie{
Name: "user",
Value: encoded,
Path: "/",
Secure: true,
HttpOnly: true,
}
http.SetCookie(w, cookie)
}
fmt.Fprintln(w, "Hello World")
}
func ReadCookieHandler(w http.ResponseWriter, r *http.Request) {
if cookie, err := r.Cookie("user"); err == nil {
u := &User{}
if err = s.Decode("user", cookie.Value, u); err == nil {
fmt.Fprintf(w, "name:%s age:%d", u.Name, u.Age)
}
}
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/set_cookie", SetCookieHandler)
r.HandleFunc("/read_cookie", ReadCookieHandler)
http.Handle("/", r)
log.Fatal(http.ListenAndServe(":8080", nil))
}
首先需要创建一个SecureCookie对象:
var s = securecookie.New(hashKey, blockKey)
其中hashKey是必填的,它用来验证 cookie 是否是伪造的,底层使用 HMAC(Hash-based message authentication code)算法。推荐hashKey使用 32/64 字节的 Key。
blockKey是可选的,它用来加密 cookie,如不需要加密,可以传nil。如果设置了,它的长度必须与对应的加密算法的块大小(block size)一致。例如对于 AES 系列算法,AES-128/AES-192/AES-256 对应的块大小分别为 16/24/32 字节。
为了方便也可以使用GenerateRandomKey()函数生成一个安全性足够强的随机 key。每次调用该函数都会返回不同的 key。上面代码就是通过这种方式创建 key 的。
调用s.Encode("user", u)将对象u编码成字符串,内部实际上使用了标准库encoding/gob。所以gob支持的类型都可以编码。
调用s.Decode("user", cookie.Value, u)将 cookie 值解码到对应的u对象中。
运行:
$ go run main.go
首先使用浏览器访问localhost:8080/set_cookie,这时可以在 Chrome 开发者工具的 Application 页签中看到 cookie 内容:

访问localhost:8080/read_cookie,页面显示name: dj age: 18。
使用 JSON
securecookie默认使用encoding/gob编码 cookie 值,我们也可以改用encoding/json。securecookie将编解码器封装成一个Serializer接口:
type Serializer interface {
Serialize(src interface{}) ([]byte, error)
Deserialize(src []byte, dst interface{}) error
}
securecookie提供了GobEncoder和JSONEncoder的实现:
func (e GobEncoder) Serialize(src interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
enc := gob.NewEncoder(buf)
if err := enc.Encode(src); err != nil {
return nil, cookieError{cause: err, typ: usageError}
}
return buf.Bytes(), nil
}
func (e GobEncoder) Deserialize(src []byte, dst interface{}) error {
dec := gob.NewDecoder(bytes.NewBuffer(src))
if err := dec.Decode(dst); err != nil {
return cookieError{cause: err, typ: decodeError}
}
return nil
}
func (e JSONEncoder) Serialize(src interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
enc := json.NewEncoder(buf)
if err := enc.Encode(src); err != nil {
return nil, cookieError{cause: err, typ: usageError}
}
return buf.Bytes(), nil
}
func (e JSONEncoder) Deserialize(src []byte, dst interface{}) error {
dec := json.NewDecoder(bytes.NewReader(src))
if err := dec.Decode(dst); err != nil {
return cookieError{cause: err, typ: decodeError}
}
return nil
}
我们可以调用securecookie.SetSerializer(JSONEncoder{})设置使用 JSON 编码:
var (
hashKey = securecookie.GenerateRandomKey(16)
blockKey = securecookie.GenerateRandomKey(16)
s = securecookie.New(hashKey, blockKey)
)
func init() {
s.SetSerializer(securecookie.JSONEncoder{})
}
自定义编解码
我们可以定义一个类型实现Serializer接口,那么该类型的对象可以用作securecookie的编解码器。我们实现一个简单的 XML 编解码器:
package main
type XMLEncoder struct{}
func (x XMLEncoder) Serialize(src interface{}) ([]byte, error) {
buf := &bytes.Buffer{}
encoder := xml.NewEncoder(buf)
if err := encoder.Encode(buf); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (x XMLEncoder) Deserialize(src []byte, dst interface{}) error {
dec := xml.NewDecoder(bytes.NewBuffer(src))
if err := dec.Decode(dst); err != nil {
return err
}
return nil
}
func init() {
s.SetSerializer(XMLEncoder{})
}
由于securecookie.cookieError未导出,XMLEncoder与GobEncoder/JSONEncoder返回的错误有些不一致,不过不影响使用。
Hash/Block 函数
securecookie默认使用sha256.New作为 Hash 函数(用于 HMAC 算法),使用aes.NewCipher作为 Block 函数(用于加解密):
// securecookie.go
func New(hashKey, blockKey []byte) *SecureCookie {
s := &SecureCookie{
hashKey: hashKey,
blockKey: blockKey,
// 这里设置 Hash 函数
hashFunc: sha256.New,
maxAge: 86400 * 30,
maxLength: 4096,
sz: GobEncoder{},
}
if hashKey == nil {
s.err = errHashKeyNotSet
}
if blockKey != nil {
// 这里设置 Block 函数
s.BlockFunc(aes.NewCipher)
}
return s
}
可以通过securecookie.HashFunc()修改 Hash 函数,传入一个func () hash.Hash类型:
func (s *SecureCookie) HashFunc(f func() hash.Hash) *SecureCookie {
s.hashFunc = f
return s
}
通过securecookie.BlockFunc()修改 Block 函数,传入一个f func([]byte) (cipher.Block, error):
func (s *SecureCookie) BlockFunc(f func([]byte) (cipher.Block, error)) *SecureCookie {
if s.blockKey == nil {
s.err = errBlockKeyNotSet
} else if block, err := f(s.blockKey); err == nil {
s.block = block
} else {
s.err = cookieError{cause: err, typ: usageError}
}
return s
}
更换这两个函数更多的是处于安全性的考虑,例如选用更安全的sha512算法:
s.HashFunc(sha512.New512_256)
更换 Key
为了防止 cookie 泄露造成安全风险,有个常用的安全策略:定期更换 Key。更换 Key,让之前获得的 cookie 失效。对应securecookie库,就是更换SecureCookie对象:
var (
prevCookie unsafe.Pointer
currentCookie unsafe.Pointer
)
func init() {
prevCookie = unsafe.Pointer(securecookie.New(
securecookie.GenerateRandomKey(64),
securecookie.GenerateRandomKey(32),
))
currentCookie = unsafe.Pointer(securecookie.New(
securecookie.GenerateRandomKey(64),
securecookie.GenerateRandomKey(32),
))
}
程序启动时,我们先生成两个SecureCookie对象,然后每隔一段时间就生成一个新的对象替换旧的。
由于每个请求都是在一个独立的 goroutine 中处理的(读),更换 key 也是在一个单独的 goroutine(写)。为了并发安全,我们必须增加同步措施。但是这种情况下使用锁又太重了,毕竟这里更新的频率很低。
我这里将securecookie.SecureCookie对象存储为unsafe.Pointer类型,然后就可以使用atomic原子操作来同步读取和更新了:
func rotateKey() {
newcookie := securecookie.New(
securecookie.GenerateRandomKey(64),
securecookie.GenerateRandomKey(32),
)
atomic.StorePointer(&prevCookie, currentCookie)
atomic.StorePointer(¤tCookie, unsafe.Pointer(newcookie))
}
rotateKey()需要在一个新的 goroutine 中定期调用,我们在main函数中启动这个 goroutine
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go RotateKey(ctx)
}
func RotateKey(ctx context.Context) {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case
<p>这里为了方便测试,我设置每隔 30s 就轮换一次。同时为了防止 goroutine 泄漏,我们传入了一个可取消的<code>Context</code>。还需要注意<code>time.NewTicker()</code>创建的<code>*time.Ticker</code>对象不使用时需要手动调用<code>Stop()</code>关闭,否则会造成资源泄漏。</p>
<p>使用两个<code>SecureCookie</code>对象之后,我们编解码可以调用<code>EncodeMulti/DecodeMulti</code>这组方法,它们可以接受多个<code>SecureCookie</code>对象:</p>
<pre class="brush:go;">func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
u := &User{
Name: "dj",
Age: 18,
}
if encoded, err := securecookie.EncodeMulti(
"user", u,
// 看这里 ?
(*securecookie.SecureCookie)(atomic.LoadPointer(¤tCookie)),
); err == nil {
cookie := &http.Cookie{
Name: "user",
Value: encoded,
Path: "/",
Secure: true,
HttpOnly: true,
}
http.SetCookie(w, cookie)
}
fmt.Fprintln(w, "Hello World")
}
使用unsafe.Pointer保存SecureCookie对象后,使用时需要类型转换。并且由于并发问题,需要使用atomic.LoadPointer()访问。
解码时调用DecodeMulti依次传入currentCookie和prevCookie,让prevCookie不会立刻失效:
func ReadCookieHandler(w http.ResponseWriter, r *http.Request) {
if cookie, err := r.Cookie("user"); err == nil {
u := &User{}
if err = securecookie.DecodeMulti(
"user", cookie.Value, u,
// 看这里 ?
(*securecookie.SecureCookie)(atomic.LoadPointer(¤tCookie)),
(*securecookie.SecureCookie)(atomic.LoadPointer(&prevCookie)),
); err == nil {
fmt.Fprintf(w, "name:%s age:%d", u.Name, u.Age)
} else {
fmt.Fprintf(w, "read cookie error:%v", err)
}
}
}
运行程序:
$ go run main.go
先请求localhost:8080/set_cookie,然后请求localhost:8080/read_cookie读取 cookie。等待 1 分钟后,再次请求,发现之前的 cookie 失效了:
read cookie error:securecookie: the value is not valid (and 1 other error)
总结
securecookie为 cookie 添加了一层保护罩,让 cookie 不能轻易地被读取和伪造。还是需要强调一下:
敏感数据不要放在 cookie 中!敏感数据不要放在 cookie 中!敏感数据不要放在 cookie 中!敏感数据不要放在 cookie 中!
重要的事情说 4 遍。在使用 cookie 存放数据时需要仔细权衡。
大家如果发现好玩、好用的 Go 语言库,欢迎到 Go 每日一库 GitHub 上提交 issue?
参考
gorilla/securecookie GitHub:github.com/gorilla/securecookie
Go 每日一库 GitHub:https://github.com/darjun/go-daily-lib
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
Gogorilla/sessions库安装使用
- 上一篇
- Gogorilla/sessions库安装使用
- 下一篇
- go goth封装第三方认证库示例详解
-
- Golang · Go教程 | 4小时前 | 格式化输出 printf fmt库 格式化动词 Stringer接口
- Golangfmt库用法与格式化技巧解析
- 140浏览 收藏
-
- Golang · Go教程 | 4小时前 |
- Golang配置Protobuf安装教程
- 147浏览 收藏
-
- Golang · Go教程 | 4小时前 |
- Golang中介者模式实现与通信解耦技巧
- 378浏览 收藏
-
- Golang · Go教程 | 4小时前 |
- Golang多协程通信技巧分享
- 255浏览 收藏
-
- Golang · Go教程 | 5小时前 |
- Golang如何判断变量类型?
- 393浏览 收藏
-
- Golang · Go教程 | 5小时前 |
- Golang云原生微服务实战教程
- 310浏览 收藏
-
- Golang · Go教程 | 5小时前 |
- Golang迭代器与懒加载结合应用
- 110浏览 收藏
-
- Golang · Go教程 | 6小时前 | 性能优化 并发安全 Golangslicemap 预设容量 指针拷贝
- Golangslicemap优化技巧分享
- 412浏览 收藏
-
- Golang · Go教程 | 6小时前 |
- Golang代理模式与访问控制实现解析
- 423浏览 收藏
-
- Golang · Go教程 | 6小时前 |
- Golang事件管理模块实现教程
- 274浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3164次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3376次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3405次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4509次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3785次使用
-
- go语言csrf库使用实现原理示例解析
- 2022-12-22 173浏览
-
- Golang 基于flag库实现一个简单命令行工具
- 2022-12-23 240浏览
-
- Gogorilla/sessions库安装使用
- 2022-12-30 470浏览
-
- go goth封装第三方认证库示例详解
- 2022-12-23 377浏览
-
- Go位集合相关操作bitset库安装使用
- 2022-12-27 343浏览

