gpt4 book ai didi

session - Gorilla session 不适用于客户端的 CORS

转载 作者:IT王子 更新时间:2023-10-29 01:06:34 26 4
gpt4 key购买 nike

我已经设置了一个 Go rest api。在登录时我这样做:

session, _ := store.New(r, sessionId)
session.Options.MaxAge = 12 * 3600
err := session.Save(r, w)
//treat error

为了检查 session ,我有这样的东西:

    session, err := store.Get(r, sessionId)
//treat error
if session.IsNew {
http.Error(w, "Unauthorized session.", http.StatusUnauthorized)
return
}

如果我执行来自 postman 的请求,它工作正常,但是当我从我的客户那里执行请求时,我得到 401。你们有没有遇到过这样的事情?该商店是一个 CookieStore。

我已经检查了 id,我用静态字符串替换了 sessionId 变量。 gorilla session 使用 gorilla 上下文来注册一个新请求,当我从 postman 那里发出请求时 context.data[r] 不是空的,但来自客户端的请求总是空的 ->总是一个新的 session 。

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 进行调试(感谢您的建议),我发现 postman 的请求有一个粗体条目 Cookies/Login 而来自客户端的请求没有。知道如何获取/设置该值吗?它以某种方式在 Postman 中自动设置。在身份验证请求中,我得到一个 set-cookie header ,其中包含我需要的所有数据,但我无法在客户端上获取它。我得到 Refused to get unsafe header set-cookie

最佳答案

问题是,在客户端中,请求需要有 withCredentials = true,然后浏览器会处理所有事情。它从 set-cookie header 获取 cookie,并通过 cookie header 发送 cookie。所以,毕竟这不是 gorilla session 问题。

关于session - Gorilla session 不适用于客户端的 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31448642/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com