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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?