dongshi3818 2016-10-31 08:29
浏览 508
已采纳

无法在Golang中的GET请求的标头中传递Bearer令牌

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 ). But it does not work using go.

Here is the code sample.

url := "http://api.kounta.com/v1/companies/me.json"

var bearer = "Bearer " + <ACCESS TOKEN HERE>
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("authorization", bearer)

client := urlfetch.Client(context)

resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()

body, _ := ioutil.ReadAll(resp.Body)
writer.Write([]byte(body)) // Gives 401 Unauthorized error, though same works using POSTMAN
  • 写回答

1条回答 默认 最新

  • duanliaolan6178 2016-12-04 05:53
    关注

    I was able to solve the problem. Actually the problem was two way.

    1) The API end point was doing a redirect (302), which was causing a 302 response and then the other API was being called.

    2) GO by default does not forward the headers, thus my bearer token was being lost in the middle.

    FIX:

    I had to override the client's CheckRedirect function and manually pass the headers to the new request.

    client.CheckRedirect = checkRedirectFunc
    

    Here is how I forwarded the headers manually.

    func checkRedirectFunc(req *http.Request, via []*http.Request) error {
        req.Header.Add("Authorization", via[0].Header.Get("Authorization"))
        return nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置