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 关于IMageEnView 图标定位问题
  • ¥20 求解答(matlab)
  • ¥30 ffmpeg库使用过程中遇到的问题
  • ¥15 pyqt5 中python如何通过Qtwebchannel主动发消息给web前端
  • ¥15 关于HTML中title获取xml内容的问题
  • ¥15 fanuc机器人PRIO083数字信号未复原错误,如何解决?
  • ¥20 如何为现有电路板增加远程控制功能
  • ¥15 UE5打包失败,求解决
  • ¥15 请问STM32G431的CANOPEN协议函数怎么写
  • ¥15 graphpad prism 三因素重复测定报错