diff --git a/zh/06.4.md b/zh/06.4.md index 3e94372a..c0b779cb 100644 --- a/zh/06.4.md +++ b/zh/06.4.md @@ -6,24 +6,24 @@ session劫持是一种广泛存在的比较严重的安全威胁,在session技 我们写了如下的代码来展示一个count计数器: ```Go - func count(w http.ResponseWriter, r *http.Request) { - 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")) +func count(w http.ResponseWriter, r *http.Request) { + 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")) +} ``` count.gtpl的代码如下所示: ```Go - Hi. Now count:{{.}} +Hi. Now count:{{.}} ``` 然后我们在浏览器里面刷新可以看到如下内容: @@ -60,27 +60,27 @@ count.gtpl的代码如下所示: 第二步就是在每个请求里面加上token,实现类似前面章节里面讲的防止form重复递交类似的功能,我们在每个请求里面加上一个隐藏的token,然后每次验证这个token,从而保证用户的请求都是唯一性。 ```Go - 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) +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) ``` ### 间隔生成新的SID 还有一个解决方案就是,我们给session额外设置一个创建时间的值,一旦过了一定的时间,我们销毁这个sessionID,重新生成新的session,这样可以一定程度上防止session劫持的问题。 ```Go - 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) - } +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的机会大大降低。