Web 开发中一个很重要的议题就是如何做好用户的整个浏览过程的控制,因为 HTTP 协议是无状态的,所以用户的每一次请求都是无状态的,我们不知道在整个 Web 操作过程中哪些连接与该用户有关,我们应该如何来解决这个问题呢?
Web 里面经典的解决方案是 cookie 和 session,cookie 机制是一种客户端机制,把用户数据保存在客户端,而 session 机制是一种服务器端的机制,服务器使用一种类似于散列表的结构来保存信息,每一个网站访客都会被分配给一个唯一的标志符,即 sessionID, 它的存放形式无非两种:要么经过 url 传递,要么保存在客户端的 cookies 里。当然,你也可以将 Session 保存到数据库里,这样会更安全,但效率方面会有所下降。
Session 和 Cookie简介
因为 HTTP 协议是无状态的,所以很显然服务器不可能知道我们已经在上一次的 HTTP 请求中通过了验证。
当然,最简单的解决方案就是所有的请求里面都带上用户名和密码,这样虽然可行,但大大加重了服务器的负担(对于每个 request 都需要到数据库验证),也大大降低了用户体验 (每个页面都需要重新输入用户名密码,每个页面都带有登录表单)。
既然直接在请求中带上用户名与密码不可行,那么就只有在服务器或客户端保存一些类似的可以代表身份的信息了,所以就有了 cookie 与 session。
cookie
cookie,简而言之就是在本地计算机保存一些用户操作的历史信息(当然包括登录信息),并在用户再次访问该站点时浏览器通过 HTTP 协议将本地 cookie 内容发送给服务器,从而完成验证,或继续上一步操作。
session
session,简而言之就是在服务器上保存用户操作的历史信息。服务器使用 session id 来标识 session,session id 由服务器负责产生,保证随机性与唯一性,相当于一个随机密钥,避免在握手或传输中暴露用户真实密码。但该方式下,仍然需要将发送请求的客户端与 session 进行对应,所以可以借助 cookie 机制来获取客户端的标识(即 session id),也可以通过 GET 方式将 id 提交给服务器。


Cookie详解
Cookie 是由浏览器维持的,存储在客户端的一小段文本信息,伴随着用户请求和页面在 Web 服务器和浏览器之间传递。用户每次访问站点时,Web 应用程序都可以读取 cookie 包含的信息。
cookie 是有时间限制的,根据生命期不同分成两种:会话 cookie 和持久 cookie;
如果不设置过期时间,则表示这个 cookie 的生命周期为从创建到浏览器关闭为止,只要关闭浏览器窗口,cookie 就消失了。这种生命期为浏览会话期的 cookie 被称为会话 cookie。会话 cookie 一般不保存在硬盘上而是保存在内存里。
如果设置了过期时间 (setMaxAge (606024)),浏览器就会把 cookie 保存到硬盘上,关闭后再次打开浏览器,这些 cookie 依然有效直到超过设定的过期时间。存储在硬盘上的 cookie 可以在不同的浏览器进程间共享,比如两个 IE 窗口。而对于保存在内存的 cookie,不同的浏览器有不同的处理方式。
Go 设置 cookie
Go 语言中通过 net/http 包中的 SetCookie 来设置:
http.SetCookie(w ResponseWriter, cookie *Cookie)
expiration := time.Now()
expiration = expiration.AddDate(1, 0, 0)
cookie := http.Cookie{Name: "username", Value: "astaxie", Expires: expiration}
http.SetCookie(w, &cookie)
Go 读取 cookie
cookie, _ := r.Cookie("username")
fmt.Fprint(w, cookie)
还有另外一种读取方式
for _, cookie := range r.Cookies() {
fmt.Fprint(w, cookie.Name)
}
Session详解
session 机制是一种服务器端的机制,服务器使用一种类似于散列表的结构 (也可能就是使用散列表) 来保存信息。
但程序需要为某个客户端的请求创建一个 session 的时候,服务器首先检查这个客户端的请求里是否包含了一个 session 标识-称为 session id,如果已经包含一个 session id 则说明以前已经为此客户创建过 session,服务器就按照 session id 把这个 session 检索出来使用 (如果检索不到,可能会新建一个,这种情况可能出现在服务端已经删除了该用户对应的 session 对象,但用户人为地在请求的 URL 后面附加上一个 JSESSION 的参数)。如果客户请求不包含 session id,则为此客户创建一个 session 并且同时生成一个与此 session 相关联的 session id,这个 session id 将在本次响应中返回给客户端保存。
session 和 cookie 的目的相同,都是为了克服 http 协议无状态的缺陷,但完成的方法不同。session 通过 cookie,在客户端保存 session id,而将用户的其他会话消息保存在服务端的 session 对象中,与此相对的,cookie 需要将所有信息都保存在客户端。因此 cookie 存在着一定的安全隐患,例如本地 cookie 中保存的用户名密码被破译,或 cookie 被其他网站收集(例如:1. appA 主动设置域 B cookie,让域 B cookie 获取;2. XSS,在 appA 上通过 javascript 获取 document.cookie,并传递给自己的 appB)。
Session 创建过程
session 的基本原理是由服务器为每个会话维护一份信息数据,客户端和服务端依靠一个全局唯一的标识来访问这份数据,以达到交互的目的。当用户访问 Web 应用时,服务端程序会随需要创建 session,这个过程可以概括为三个步骤:
- 生成全局唯一标识符(sessionid);
- 开辟数据存储空间。一般会在内存中创建相应的数据结构,但这种情况下,系统一旦掉电,所有的会话数据就会丢失,如果是电子商务类网站,这将造成严重的后果。所以为了解决这类问题,你可以将会话数据写到文件里或存储在数据库中,当然这样会增加 I/O 开销,但是它可以实现某种程度的 session 持久化,也更有利于 session 的共享;
- 将 session 的全局唯一标示符发送给客户端。
发送Session的方式
考虑到 HTTP 协议的定义,数据无非可以放到请求行、头域或 Body 里。
因此发送这个 session 的唯一标识的常用方式有以下两种
Cookie
服务端通过设置 Set-cookie 头就可以将 session 的标识符传送到客户端,而客户端此后的每一次请求都会带上这个标识符,另外一般包含 session 信息的 cookie 会将失效时间设置为 0 (会话 cookie),即浏览器进程有效时间。至于浏览器怎么处理这个 0,每个浏览器都有自己的方案,但差别都不会太大 (一般体现在新建浏览器窗口的时候);
URL 重写
所谓 URL 重写,就是在返回给用户的页面里的所有的 URL 后面追加 session 标识符,这样用户在收到响应之后,无论点击响应页面里的哪个链接或提交表单,都会自动带上 session 标识符,从而就实现了会话的保持。虽然这种做法比较麻烦,但是,如果客户端禁用了 cookie 的话,此种方案将会是首选。
Session 管理设计
session 管理涉及到如下几个因素
- 全局 session 管理器
- 保证 sessionid 的全局唯一性
- 为每个客户关联一个 session
- session 的存储 (可以存储到内存、文件、数据库等)
- session 过期处理
Session 管理器
定义一个全局的 session 管理器
type Manager struct {
cookieName string // private cookiename
lock sync.Mutex // protects session
provider Provider
maxLifeTime int64
}
func NewManager(provideName, cookieName string, maxLifeTime int64) (*Manager, error) {
provider, ok := provides[provideName]
if !ok {
return nil, fmt.Errorf("session: unknown provide %q (forgotten import?)", provideName)
}
return &Manager{provider: provider, cookieName: cookieName, maxLifeTime: maxLifeTime}, nil
}
Go 实现整个的流程,在 main 包中创建一个全局的 session 管理器
var globalSessions *session.Manager
// 然后在 init 函数中初始化
func init() {
globalSessions, _ = NewManager("memory", "gosessionid", 3600)
}
我们知道 session 是保存在服务器端的数据,它可以以任何的方式存储,比如存储在内存、数据库或者文件中。因此我们抽象出一个 Provider 接口,用以表征 session 管理器底层存储结构。
type Provider interface {
SessionInit(sid string) (Session, error)
SessionRead(sid string) (Session, error)
SessionDestroy(sid string) error
SessionGC(maxLifeTime int64)
}
- SessionInit 函数实现 Session 的初始化,操作成功则返回此新的 Session 变量
- SessionRead 函数返回 sid 所代表的 Session 变量,如果不存在,那么将以 sid 为参数调用 SessionInit 函数创建并返回一个新的 Session 变量
- SessionDestroy 函数用来销毁 sid 对应的 Session 变量
- SessionGC 根据 maxLifeTime 来删除过期的数据
对 Session 的处理基本就设置值、读取值、删除值以及获取当前 sessionID 这四个操作,所以我们的 Session 接口也就实现这四个操作。
type Session interface {
Set(key, value interface{}) error // set session value
Get(key interface{}) interface{} // get session value
Delete(key interface{}) error // delete session value
SessionID() string // back current sessionID
}
将provider注册进全局变量,让Manage能按名称找到Provider
var provides = make(map[string]Provider)
func Register(name string, provider Provider) {
if provider == nil {
panic("session: Register provider is nil")
}
if _, dup := provides[name]; dup {
panic("session: Register called twice for provider " + name)
}
provides[name] = provider
}
唯一的 Session ID
设置唯一的ID
func (manager *Manager) sessionId() string {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return ""
}
return base64.URLEncoding.EncodeToString(b)
}
Session 创建
我们需要为每个来访用户分配或获取与他相关连的 Session,以便后面根据 Session 信息来验证操作。SessionStart 这个函数就是用来检测是否已经有某个 Session 与当前来访用户发生了关联,如果没有则创建之。
func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session Session) {
manager.lock.Lock()
defer manager.lock.Unlock()
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
sid := manager.sessionId()
session, _ = manager.provider.SessionInit(sid)
cookie := http.Cookie{Name: manager.cookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, MaxAge: int(manager.maxLifeTime)}
http.SetCookie(w, &cookie)
} else {
sid, _ := url.QueryUnescape(cookie.Value)
session, _ = manager.provider.SessionRead(sid)
}
return
}
r.Cookie(name) 是 从浏览器发送的请求里,取出某个 Cookie(看浏览器是否存在带着名字为 manager.cookieName 的 Cookie )
- 如果找到 → 返回这个 cookie
- 如果找不到 → 返回 error(比如 http.ErrNoCookie)
创建逻辑:先注册sessionId,再在后端(内存 / redis / 文件)里创建一个新的 Session 对象,创建 Cookie 对象(告诉浏览器保存 sid),最后把这个 Cookie 发送给浏览器
已存在逻辑:sid, _ := url.QueryUnescape(cookie.Value),解码,取出sessionid,再从后端存储中读取 session 数据
使用注册的session
func login(w http.ResponseWriter, r *http.Request) {
sess := globalSessions.SessionStart(w, r)
r.ParseForm()
if r.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
w.Header().Set("Content-Type", "text/html")
t.Execute(w, sess.Get("username"))
} else {
sess.Set("username", r.Form["username"])
http.Redirect(w, r, "/", 302)
}
}
对 session 数据进行操作
func count(w http.ResponseWriter, r *http.Request) {
sess := globalSessions.SessionStart(w, r)
createtime := sess.Get("createtime")
if createtime == nil {
sess.Set("createtime", time.Now().Unix())
} else if (createtime.(int64) + 360) < (time.Now().Unix()) {
globalSessions.SessionDestroy(w, r)
sess = globalSessions.SessionStart(w, r)
}
ct := sess.Get("countnum")
if ct == nil {
sess.Set("countnum", 1)
} else {
sess.Set("countnum", (ct.(int) + 1))
}
t, _ := template.ParseFiles("count.gtpl")
w.Header().Set("Content-Type", "text/html")
t.Execute(w, sess.Get("countnum"))
}
Session 重置
我们知道,Web 应用中有用户退出这个操作,那么当用户退出应用的时候,我们需要对该用户的 session 数据进行销毁操作,下面这个函数就是实现了这个功能:
// Destroy sessionid
func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request){
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
return
} else {
manager.lock.Lock()
defer manager.lock.Unlock()
manager.provider.SessionDestroy(cookie.Value)
expiration := time.Now()
cookie := http.Cookie{Name: manager.cookieName, Path: "/", HttpOnly: true, Expires: expiration, MaxAge: -1}
http.SetCookie(w, &cookie)
}
}
Session 销毁
func init() {
go globalSessions.GC()
}
func (manager *Manager) GC() {
manager.lock.Lock()
defer manager.lock.Unlock()
manager.provider.SessionGC(manager.maxLifeTime)
time.AfterFunc(time.Duration(manager.maxLifeTime), func() { manager.GC() })
}
我们可以看到 GC 充分利用了 time 包中的定时器功能,当超时 maxLifeTime 之后调用 GC 函数,这样就可以保证 maxLifeTime 时间内的 session 都是可用的,类似的方案也可以用于统计在线用户数之类的。
Session 存储
示例一个基于内存的 session 存储接口的实现
package memory
import (
"container/list"
"github.com/astaxie/session"
"sync"
"time"
)
var pder = &Provider{list: list.New()}
type SessionStore struct {
sid string // session id唯一标示
timeAccessed time.Time // 最后访问时间
value map[interface{}]interface{} // session里面存储的值
}
func (st *SessionStore) Set(key, value interface{}) error {
st.value[key] = value
pder.SessionUpdate(st.sid)
return nil
}
func (st *SessionStore) Get(key interface{}) interface{} {
pder.SessionUpdate(st.sid)
if v, ok := st.value[key]; ok {
return v
} else {
return nil
}
}
func (st *SessionStore) Delete(key interface{}) error {
delete(st.value, key)
pder.SessionUpdate(st.sid)
return nil
}
func (st *SessionStore) SessionID() string {
return st.sid
}
type Provider struct {
lock sync.Mutex // 用来锁
sessions map[string]*list.Element // 用来存储在内存
list *list.List // 用来做 gc
}
func (pder *Provider) SessionInit(sid string) (session.Session, error) {
pder.lock.Lock()
defer pder.lock.Unlock()
v := make(map[interface{}]interface{}, 0)
newsess := &SessionStore{sid: sid, timeAccessed: time.Now(), value: v}
element := pder.list.PushFront(newsess)
pder.sessions[sid] = element
return newsess, nil
}
func (pder *Provider) SessionRead(sid string) (session.Session, error) {
if element, ok := pder.sessions[sid]; ok {
return element.Value.(*SessionStore), nil
} else {
sess, err := pder.SessionInit(sid)
return sess, err
}
return nil, nil
}
func (pder *Provider) SessionDestroy(sid string) error {
if element, ok := pder.sessions[sid]; ok {
delete(pder.sessions, sid)
pder.list.Remove(element)
return nil
}
return nil
}
func (pder *Provider) SessionGC(maxlifetime int64) {
pder.lock.Lock()
defer pder.lock.Unlock()
for {
element := pder.list.Back()
if element == nil {
break
}
if (element.Value.(*SessionStore).timeAccessed.Unix() + maxlifetime) < time.Now().Unix() {
pder.list.Remove(element)
delete(pder.sessions, element.Value.(*SessionStore).sid)
} else {
break
}
}
}
func (pder *Provider) SessionUpdate(sid string) error {
pder.lock.Lock()
defer pder.lock.Unlock()
if element, ok := pder.sessions[sid]; ok {
element.Value.(*SessionStore).timeAccessed = time.Now()
pder.list.MoveToFront(element)
return nil
}
return nil
}
func init() {
pder.sessions = make(map[string]*list.Element, 0)
session.Register("memory", pder)
}
import 的时候已经执行了 memory 函数里面的 init 函数,这样就已经注册到 session 管理器中,我们就可以使用了
import (
"github.com/astaxie/session"
_ "github.com/astaxie/session/providers/memory"
)
初始化一个 session 管理器
var globalSessions *session.Manager
// 然后在 init 函数中初始化
func init() {
globalSessions, _ = session.NewManager("memory", "gosessionid", 3600)
go globalSessions.GC()
}
预防 session 劫持
session 劫持是一种广泛存在的比较严重的安全威胁,在 session 技术中,客户端和服务端通过 session 的标识符来维护会话, 但这个标识符很容易就能被嗅探到,从而被其他人利用。它是中间人攻击的一种类型。
如何有效的防止 session 劫持
一个解决方案就是 sessionID 的值只允许 cookie 设置,而不是通过 URL 重置方式设置,同时设置 cookie 的 httponly 为 true, 这个属性是设置是否可通过客户端脚本访问这个设置的 cookie,第一这个可以防止这个 cookie 被 XSS 读取从而引起 session 劫持,第二 cookie 设置不会像 URL 重置方式那么容易获取 sessionID。
第二步就是在每个请求里面加上 token,实现类似前面章节里面讲的防止 form 重复递交类似的功能,我们在每个请求里面加上一个隐藏的 token,然后每次验证这个 token,从而保证用户的请求都是唯一性。
h := md5.New()
salt:="astaxie%^7&8888"
io.WriteString(h,salt+time.Now().String())
token:=fmt.Sprintf("%x",h.Sum(nil))
if r.Form["token"]!=token{
// 提示登录
}
sess.Set("token",token)
还有一个解决方案就是,我们给 session 额外设置一个创建时间的值,一旦过了一定的时间,我们销毁这个 sessionID,重新生成新的 session,这样可以一定程度上防止 session 劫持的问题。
createtime := sess.Get("createtime")
if createtime == nil {
sess.Set("createtime", time.Now().Unix())
} else if (createtime.(int64) + 60) < (time.Now().Unix()) {
globalSessions.SessionDestroy(w, r)
sess = globalSessions.SessionStart(w, r)
}
session 启动后,我们设置了一个值,用于记录生成 sessionID 的时间。通过判断每次请求是否过期 (这里设置了 60 秒) 定期生成新的 ID,这样使得攻击者获取有效 sessionID 的机会大大降低。
上面两个手段的组合可以在实践中消除 session 劫持的风险,一方面,由于 sessionID 频繁改变,使攻击者难有机会获取有效的 sessionID;另一方面,因为 sessionID 只能在 cookie 中传递,然后设置了 httponly,所以基于 URL 攻击的可能性为零,同时被 XSS 获取 sessionID 也不可能。最后,由于我们还设置了 MaxAge=0,这样就相当于 session cookie 不会留在浏览器的历史记录里面。
5万+

被折叠的 条评论
为什么被折叠?



