英文:
Not able to pass Bearer token in headers of a GET request in Golang
问题
我正在使用oauth2访问第三方API。我可以成功获取访问令牌,但是当我尝试通过在请求头中传递令牌来调用API时,它给我返回401(未经授权)错误。尽管我在POSTMAN中尝试通过传递头部(Authorization: Bearer <ACCESS_TOKEN>)时可以正常工作,但是在使用go时却不起作用。
以下是代码示例:
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)) // 尽管在POSTMAN中可以正常工作,但是这里返回401未经授权错误
英文:
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 <ACCESS_TOKE>). 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
得分: 16
我能解决这个问题。实际上,问题有两个方面。
1)API端点进行了重定向(302),导致返回302响应,然后调用了另一个API。
2)GO默认不会转发头部信息,因此我的Bearer令牌在中间丢失了。
修复方法:
我需要重写客户端的CheckRedirect函数,并手动将头部信息传递给新的请求。
client.CheckRedirect = checkRedirectFunc
以下是我如何手动转发头部信息的代码。
func checkRedirectFunc(req *http.Request, via []*http.Request) error {
req.Header.Add("Authorization", via[0].Header.Get("Authorization"))
return nil
}
英文:
I was able to solve the problem. Actually the problem was two way.
-
The API end point was doing a redirect (302), which was causing a 302 response and then the other API was being called.
-
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论