3

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

4

2 回答 2

3

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

于 2015-07-20T06:07:26.590 回答
0

如果其他人遇到与我相同的问题,并且您想将所有域/通配符列入白名单(或在阵列中有一个可以扫描的域列表),您可以执行类似的操作。

domain_raw := r.Host
domain_host_parts := strings.Split(domain_raw, ".")
domain := domain_host_parts[1] + "." + domain_host_parts[2]
domains := getDomains() // stores a slice of all your allowable domains
has_domain := false
for _, d := range domains {
    if d == domain {
        has_domain = true
        break
    }
}

if has_domain == false {
    return
} else {
    w.Header().Add("Access-Control-Allow-Origin", "https://"+domain_raw)
    w.Header().Add("Access-Control-Allow-Credentials", "true")
}

我爱去

于 2017-10-12T23:25:00.043 回答