Go服务器未在后续REST调用中返回Cookie
时间:2024-03-28
浏览:226
作者:佚名
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《Go服务器未在后续REST调用中返回Cookie》,聊聊,我们一起来看看吧!
我正在探索 oauth2 身份验证并设置一个使用 github 进行身份验证的服务器。我按照这个例子,并且能够让它工作。我想继续提出一些建议,实现一个基本的会话令牌系统,并从我的服务器进行 github 调用,而不是向客户端发送授权令牌。
这是我稍微修改过的 /oauth/redirect 处理程序
func oauthredirecthandler(w http.responsewriter, r *http.request) {
fmt.println("/oauth/redirect")
err := r.parseform()
if err != nil {
fmt.fprintf(os.stdout, "could not parse query: %+v", err)
w.writeheader(http.statusbadrequest)
}
code := r.formvalue("code")
requrl := fmt.sprintf("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", clientid, clientsecret, code)
req, err := http.newrequest(http.methodpost, requrl, nil)
if err != nil {
fmt.fprintf(os.stdout, "could not create http request: %v", err)
w.writeheader(http.statusbadrequest)
}
req.header.set("accept", "application/json")
res, err := httpclient.do(req)
if err != nil {
fmt.fprintf(os.stdout, "could not send http request: %+v", err)
w.writeheader(http.statusinternalservererror)
}
defer res.body.close()
var t oauthaccessresponse
if err := json.newdecoder(res.body).decode(&t); err != nil {
fmt.fprintf(os.stdout, "could not parse json response: %+v", err)
w.writeheader(http.statusbadrequest)
}
newsession := sessiontracker{
accesstoken: accesstoken,
timeout: time.now().add(time.minute * 15),
}
sessiontoken := uuid.new().string()
sessiontrackercache[sessiontoken] = newsession
http.setcookie(w, &http.cookie{
name: sessiontokenconst,
value: sessiontoken,
expires: newsession.timeout,
domain: "localhost",
})
http.redirect(w, r, "/welcome.html", http.statusfound)
}
它会重定向到带有附加 cookie 的欢迎页面,其中包含我的 sessiontoken id。
这是我的welcomehandler
func welcomeHandler(w http.ResponseWriter, req *http.Request) {
fmt.Println("/welcome")
cookie, err := req.Cookie(sessionTokenConst)
if err != nil {
fmt.Fprintf(os.Stdout, "no cookie attached: %+v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
dat, err := ioutil.ReadFile("./public/welcome.html")
if err != nil {
fmt.Fprintf(os.Stdout, "could not read welcome page: %+v", err)
w.WriteHeader(http.StatusInternalServerError)
}
fmt.Fprintf(w, string(dat))
}
观察浏览器的网络选项卡,我使用 github 进行身份验证,并且我的服务器能够看到授权令牌。 oauthredirecthandler 末尾的重定向响应包含带有 sessionid 的 cookie。我的问题在于浏览器似乎没有在对 /welcome.html 的 get 调用上附加令牌。我可以在浏览器和welcomehandler 中确认这一点。
这都是本地托管的。
我不确定这是否是我的服务器、浏览器的问题,或者我是否理解浏览器将 cookie 应用到任何未来的客户端请求,直到 cookie 过期日期错误为止。
感谢任何帮助!
解决方案
浏览器默认将cookie路径设置为请求路径。将路径设置为“/”以使 cookie 在整个网站上可用。
不要设置域名,除非您有明确的理由这样做(感谢 volker 注意到这一点)。
http.SetCookie(w, &http.Cookie{
Name: sessionTokenConst,
Value: sessionToken,
Path: "/", // <--- add this line
Expires: newSession.TimeOut,
// Domain: "localhost", <-- Remove this line
})本篇关于《Go服务器未在后续REST调用中返回Cookie》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
