Not able to pass Bearer token in headers of a GET request in Golang

xuanbao · · 721 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I am using oauth2 to access a third party API. I can get the access token alright, but when I try to call the API by passing the bearer token in the request headers it gives me 401 (Unauthorized) error. Although it works well when I try to do it via POSTMAN by passing headers as (Authorization: Bearer &lt;ACCESS_TOKE&gt;). But it does not work using go.</p> <p>Here is the code sample.</p> <pre><code> url := &#34;http://api.kounta.com/v1/companies/me.json&#34; </code></pre> <p>var bearer = &#34;Bearer &#34; + &lt;ACCESS TOKEN HERE&gt; req, err := http.NewRequest(&#34;GET&#34;, url, nil) req.Header.Add(&#34;authorization&#34;, bearer)</p> <p>client := urlfetch.Client(context)</p> <p>resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close()</p> <p>body, _ := ioutil.ReadAll(resp.Body) writer.Write([]byte(body)) // Gives 401 Unauthorized error, though same works using POSTMAN</p> <hr/>**评论:**<br/><br/>knotdjb: <pre><p>Pretty sure this is a case where you&#39;d want to use <a href="https://godoc.org/golang.org/x/oauth2" rel="nofollow">oauth2 package</a>.</p></pre>chrj: <pre><p>Have you tried inspecting the network traffic? Does the request contain the extra header?</p> <p>What&#39;s <code>urlfetch</code>?</p></pre>postman_: <pre><p>Check for redirections.</p></pre>gohacker: <pre><p>This. Try to add the following before <code>client.Do()</code>:</p> <pre><code>client.CheckRedirect = func (req *http.Request, via []*http.Request) error { if len(via) &gt; 15 { return fmt.Errorf(&#34;%d consecutive redirects&#34;, len(via)) } if len(via) == 0 { return nil } for key, val := range via[0].Header { req.Header[key] = val } return nil } </code></pre></pre>thisthat_bot: <pre><p>That.</p></pre>UnknownTed: <pre><p>Maybe it&#39;s the lowercase &#34;a&#34; from &#34;authorization&#34;.</p> <blockquote> <p>Although it works well when I try to do it via POSTMAN by passing headers as (<strong>A</strong>uthorization: Bearer &lt;ACCESS_TOKE&gt;).</p> </blockquote></pre>PaluMacil: <pre><p>Without time to test this morning, I wondered about the &#39;A&#39; as well.</p></pre>metamatic: <pre><p>-&gt; Bearer &lt;ACCESS TOKE&gt;<br/> &lt;- HTTP 420</p></pre>ultra_brite: <pre><p>might be appengine related, the standard environment is complete crap and will rewrite your outbond requests to prevent from doing what you want. Check the list of headers that may be censored.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

721 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传