我已经设置了一个 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 行
用于 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。