Go 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(&currentCookie, 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 <-ctx.Done(): break case <-ticker.C: } rotateKey() } }
这里为了方便测试,我设置每隔 30s 就轮换一次。同时为了防止 goroutine 泄漏,我们传入了一个可取消的Context
。还需要注意time.NewTicker()
创建的*time.Ticker
对象不使用时需要手动调用Stop()
关闭,否则会造成资源泄漏。
使用两个SecureCookie
对象之后,我们编解码可以调用EncodeMulti/DecodeMulti
这组方法,它们可以接受多个SecureCookie
对象:
func SetCookieHandler(w http.ResponseWriter, r *http.Request) { u := &User{ Name: "dj", Age: 18, } if encoded, err := securecookie.EncodeMulti( "user", u, // 看这里
原文出处:https://segmentfault.com/a/1190000040391049
相关文章
- 操作类就是把一些常用的一系列的数据库或相关操作写在一个类中,这样调用时我们只要调用类文件,如果要执行相关操作就直接调用类文件中的方法函数就可以实现了,下面整理了...2016-11-25
- 本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
- 这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
- 在程序员中,尤其是go新手,经常听到的一个讨论话题是:如何处理错误,这篇文章主要给大家介绍了关于Go应用中优雅处理Error的一些相关技巧,需要的朋友可以参考下...2021-09-08
- 这篇文章主要介绍了Intellij IDEA连接Navicat数据库的方法,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借价值,需要的朋友可以参考下...2021-03-25
- 在开发过程中,我们经常会将日期时间的毫秒数存放到数据库,但是它对应的时间看起来就十分不方便,我们可以使用一些函数将毫秒转换成date格式。 一、 在MySQL中,有内置的函数from_unixtime()来做相应的转换,使用如下: 复制...2014-05-31
- C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
- 通过内网连另外一台机器的mysql服务, 确发现速度N慢! 等了大约几十秒才等到提示输入密码。 但是ping mysql所在服务器却很快! 想到很久之前有过类似的经验, telnet等一些服务在连接请求的时候,会做一些反向域名解析(如果...2015-10-21
- 某些时候,例如为了搭建一个测试环境,或者克隆一个网站,需要复制一个已存在的mysql数据库。使用以下方法,可以非常简单地实现。假设已经存在的数据库名字叫db1,想要复制一份,命名为newdb。步骤如下:1. 首先创建新的数据库newd...2015-10-21
- mysqldump命令的用法1、导出所有库系统命令行mysqldump -uusername -ppassword --all-databases > all.sql 2、导入所有库mysql命令行mysql>source all.sql; 3、导出某些库系统命令行mysqldump -uusername -ppassword...2015-10-21
- 1005:创建表失败1006:创建数据库失败1007:数据库已存在,创建数据库失败1008:数据库不存在,删除数据库失败1009:不能删除数据库文件导致删除数据库失败1010:不能删除数据目录导致删除数据库失败1011:删除数据库...2013-09-23
- 这篇文章主要介绍了C++万能库头文件在vs中的安装步骤(图文),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-23
Django def clean()函数对表单中的数据进行验证操作
这篇文章主要介绍了Django def clean()函数对表单中的数据进行验证操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-07-09- 这篇文章主要介绍了c#从数据库里取得数据并异步更新ui的方法,大家参考使用吧...2020-06-25
- yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2使用中的一些基本的增删改查操作。 User::find()->all(); //返回所有用户数据; User::findOne($id); //返回 主键...2015-11-24
- 这篇文章主要介绍了springBoot 项目排除数据库启动方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-10
- 1.用phpmyadmin创建数据库和数据表 创建数据库的时候,请将“整理”设置为:“utf8_general_ci” 或执行语句: 复制代码 代码如下:CREATE DATABASE `dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; 创...2015-10-21
- 本文给大家分享基于js实现仿百度文库评分功能,代码简单易懂,非常不错,具有参考借鉴价值,需要的的朋友参考下吧...2017-01-16
- 这篇文章主要介绍了Linux 下使用shell脚本定时维护数据库,本文通过案例分析给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-11
- 今天带大家来学习selenium库的使用方法及相关知识总结,文中非常详细的介绍了selenium库,对正在学习python的小伙伴很有帮助,需要的朋友可以参考下...2021-05-25