1.7 会话管理

1.7.1【必须】安全维护session信息

  • 用户登录时应重新生成session,退出登录后应清理session。 ```go import ( “net/http” “github.com/gorilla/mux” “github.com/gorilla/handlers” )

//创建cookie func setToken(res http.ResponseWriter, req http.Request) { expireToken := time.Now().Add(time.Minute 30).Unix() expireCookie := time.Now().Add(time.Minute * 30) … cookie := http.Cookie{ Name: “Auth”, Value: signedToken, Expires: expireCookie, // 过期失效 HttpOnly: true, Path: “/“, Domain: “127.0.0.1”, Secure: true }

  1. http.SetCookie(res, &cookie)
  2. http.Redirect(res, req, "/profile", 307)

} // 删除cookie func logout(res http.ResponseWriter, req *http.Request) { deleteCookie := http.Cookie{ Name: “Auth”, Value: “none”, Expires: time.Now() } http.SetCookie(res, &deleteCookie) return }

  1. #### 1.7.2【必须】CSRF防护
  2. - 涉及系统敏感操作或可读取敏感信息的接口应校验`Referer`或添加`csrf_token`
  3. ```go
  4. // good
  5. import (
  6. "net/http"
  7. "github.com/gorilla/csrf"
  8. "github.com/gorilla/mux"
  9. )
  10. func main() {
  11. r := mux.NewRouter()
  12. r.HandleFunc("/signup", ShowSignupForm)
  13. r.HandleFunc("/signup/post", SubmitSignupForm)
  14. //使用csrf_token验证
  15. http.ListenAndServe(":8000",
  16. csrf.Protect([]byte("32-byte-long-auth-key"))(r))
  17. }