Crumb with Golang's net/http header

huangapple go评论89阅读模式
英文:

Crumb with Golang's net/http header

问题

我正在为与Jenkins RESTful API(https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API)交互的Golang代码添加面包屑CSRF保护支持。

结构体:

type Crumb struct {
  Crumb               string      `json:"crumb"`
  CrumbRequestField   string      `json:"crumbRequestField"`
}

代码:

...
crb := Crumb{}
// 对面包屑进行Golang结构体的json化处理
// https://jenkins.mydomain.com/crumbIssuer/api/json
...

if crb.Crumb != "" && crb.CrumbRequestField != "" {
  req.Header.Set(crb.CrumbRequestField, crb.Crumb)
}

req.SetBasicAuth(jenkins.auth.Username, jenkins.auth.ApiToken)

// 我认为问题与DefaultClient有关,但不确定
return http.DefaultClient.Do(req)

但是,使用上述的Golang实现时,一直收到403错误,但使用cURL调用却正常工作。

cURL日志:

> POST /computer/node1/toggleOffline HTTP/1.1
> Authorization: Basic <key>
> User-Agent: curl/7.30.0
> Host: jenkins.mydomain.com
> Accept: */*
> .crumb: 0d6401898751f250ff1f95b5bf9589db
英文:

I was adding crumb CSRF protection support as part of the Golang code I wrote for interacting with Jenkins RESTful API (https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API)

struct:

type Crumb struct {
  Crumb               string      `json:&quot;crumb&quot;`
  CrumbRequestField   string      `json:&quot;crumbRequestField&quot;`
}

code

  ...
  crb := Crumb{}
  // did some work to jsonify the crumb to Golang struct
  // https://jenkins.mydomain.com/crumbIssuer/api/json
  ...


  if (crb.Crumb != &quot;&quot; &amp;&amp; crb.CrumbRequestField != &quot;&quot; ) {
    req.Header.Set(crb.CrumbRequestField, crb.Crumb)
  }

  req.SetBasicAuth(jenkins.auth.Username, jenkins.auth.ApiToken)

  // i think the issue is related to DefaultClient, but not sure
  return http.DefaultClient.Do(req) 

But with Golang implementation above keep getting 403, but the same thing works fine with cURL call.

&amp;{403 No valid crumb was included in the request 403 HTTP/1.1 1 1 map[Server:[nginx] Date:[Thu, 31 Jul 2014 05:58:52 GMT] Content-Type:[text/html;charset=ISO-8859-1] Connection:[keep-alive] Cache-Control:[must-revalidate,no-cache,no-store]] 0xc20800ff80 -1 [chunked] false map[] 0xc2082ba270 0xc208005da0}

cURL log:

&gt; POST /computer/node1/toggleOffline HTTP/1.1
&gt; Authorization: Basic &lt;key&gt;
&gt; User-Agent: curl/7.30.0
&gt; Host: jenkins.mydomain.com
&gt; Accept: */*
&gt; .crumb: 0d6401898751f250ff1f95b5bf9589db

答案1

得分: 1

我在这里回答自己的问题。我找到了问题所在,与Golang的net/http库无关。Jenkins的crumb GET请求要求您提供基本身份验证以正确获取crumb。

英文:

I'm answering my own question here. I found my issue and it has nothing related to Golang's net/http lib. The Jenkins crumb GET request required that you need to provide basic auth to obtain properly crumb.

huangapple
  • 本文由 发表于 2014年7月31日 14:37:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/25052286.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定