Go

大猩猩会话不适用于客户的CORS

发布于 2021-02-01 10:40:26

我已经设置了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变量替换为静态字符串。大猩猩会话使用大猩猩上下文注册一个新请求,当我这样做时,来自邮递员的请求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,而客户端的请求则没有。任何想法如何获得/设置该值?它是通过邮递员自动设置的。在身份验证请求中,我得到一个set-
cookie标头,其中包含我需要的所有数据,但无法在客户端上获取。我懂了Refused to get unsafe header set-cookie

关注者
0
被浏览
81
1 个回答
  • 面试哥
    面试哥 2021-02-01
    为面试而生,有面试问题,就找面试哥。

    问题在于,客户端需要具有请求withCredentials = true,然后浏览器才能处理所有内容。它从头获取cookie,set- cookie并通过cookie头发送cookie 。因此,毕竟这不是大猩猩会议的问题。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看