会话管理
1.【必须】安全维护session信息
- 用户登录时应重新生成session,退出登录后应清理session。
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
}
2.【必须】CSRF防护
- 涉及系统敏感操作或可读取敏感信息的接口应校验
Referer
或添加csrf_token
。
// 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))
}
最后编辑: kuteng 文档更新时间: 2021-06-04 17:24 作者:kuteng