Not able to pass Bearer token in headers of a GET request in Golang

▼魔方 西西 提交于 2019-12-11 03:52:47

问题


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:


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
}


来源:https://stackoverflow.com/questions/40338711/not-able-to-pass-bearer-token-in-headers-of-a-get-request-in-golang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!