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 }
http.SetCookie(res, &cookie)
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.7.2【必须】CSRF防护
- 涉及系统敏感操作或可读取敏感信息的接口应校验`Referer`或添加`csrf_token`。
```go
// good
import (
"net/http"
"github.com/gorilla/csrf"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/signup", ShowSignupForm)
r.HandleFunc("/signup/post", SubmitSignupForm)
//使用csrf_token验证
http.ListenAndServe(":8000",
csrf.Protect([]byte("32-byte-long-auth-key"))(r))
}