<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 <ACCESS_TOKE>). But it does not work using go.</p>
<p>Here is the code sample.</p>
<pre><code> url := "http://api.kounta.com/v1/companies/me.json"
</code></pre>
<p>var bearer = "Bearer " + <ACCESS TOKEN HERE>
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("authorization", 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'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'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) > 15 {
return fmt.Errorf("%d consecutive redirects", 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's the lowercase "a" from "authorization".</p>
<blockquote>
<p>Although it works well when I try to do it via POSTMAN by passing headers as (<strong>A</strong>uthorization: Bearer <ACCESS_TOKE>).</p>
</blockquote></pre>PaluMacil: <pre><p>Without time to test this morning, I wondered about the 'A' as well.</p></pre>metamatic: <pre><p>-> Bearer <ACCESS TOKE><br/>
<- 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
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传