【发布时间】:2015-10-05 13:41:22
【问题描述】:
我已经设置了一个 Go rest api。在登录时我这样做:
session, _ := store.New(r, sessionId)
session.Options.MaxAge = 12 * 3600
err := session.Save(r, w)
//treat error
为了检查会话,我有这样的感觉:
session, err := store.Get(r, sessionId)
//treat error
if session.IsNew {
http.Error(w, "Unauthorized session.", http.StatusUnauthorized)
return
}
如果我从邮递员那里发出请求,它工作正常,但是当我从我的客户那里发出请求时,我得到 401。你们中有人经历过这样的事情吗?该商店是一个 CookieStore。
我已经检查了 id,我用静态字符串替换了 sessionId 变量。 Gorilla 会话使用 gorilla 上下文注册新请求,当我从邮递员 context.data[r] 发出请求时,它不为空,但从客户端它始终为空 -> 始终为新会话。
https://github.com/gorilla/context/blob/master/context.go - 第 33 行
它被调用
https://github.com/gorilla/sessions/blob/master/sessions.go - 第 122 行
wich 用在 CookieStore.Get 函数中
https://github.com/gorilla/sessions/blob/master/store.go - 第 77 行
编辑 1: 对于我使用聚合物的客户端,我也尝试了 xmlhttp。 聚合物:
<iron-ajax
id="ajaxRequest"
auto
url="{{requestUrl}}"
headers="{{requestHeaders}}"
handle-as="json"
on-response="onResponse"
on-error="onError"
content-type="application/json"
>
</iron-ajax>
和处理程序
onResponse: function(response){
console.log(response.detail.response);
this.items = response.detail.response
},
onError: function(error){
console.log(error.detail)
},
ready: function(){
this.requestUrl = "http://localhost:8080/api/fingerprint/company/" + getCookie("companyId");
this.requestHeaders = {"Set-cookie": getCookie("api_token")}
}
cookie 成功到达后端。
还有xmlhttp:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
//do stuff
}else if(xmlhttp.status == 401){
page.redirect("/unauthorized")
}else{
page.redirect("/error")
}
}
}
xmlhttp.open("GET","http://localhost:8080/api/fingerprint/company/" + getCookie("companyId"),true);
xmlhttp.setRequestHeader("Set-cookie", getCookie("api_token"));
xmlhttp.send();
编辑 2:
所以我尝试使用 fiddler 进行调试(感谢您的建议),我发现邮递员的请求有一个粗体条目 Cookies / Login,而来自客户端的请求没有。知道如何获取/设置该值吗?它以某种方式在 Postman 中自动设置。在身份验证请求中,我得到一个 set-cookie 标头,其中包含我需要的所有数据,但我无法在客户端上获取它。我得到Refused to get unsafe header set-cookie。
【问题讨论】:
-
看起来这可能是您的客户端如何处理 cookie 的问题。可以添加客户端代码吗?
-
您可以使用 fiddler 之类的其他工具来检查并提供这两种情况的请求标头和正文吗?我解决这个问题的方法是,摆弄每一个,将数据复制到文本编辑器中,比较两者,使我的客户请求与 Postmans 相同。
-
当您从“客户端”说时,这是在同一个域上吗?听起来不是。
-
标题中有CORS这个词=>不是同一个域