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

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格