无法在Golang的GET请求头中传递Bearer令牌。

huangapple go评论84阅读模式
英文:

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 := &quot;http://api.kounta.com/v1/companies/me.json&quot;

var bearer = &quot;Bearer &quot; + &lt;ACCESS TOKEN HERE&gt;
req, err := http.NewRequest(&quot;GET&quot;, url, nil)
req.Header.Add(&quot;authorization&quot;, 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.

  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(&quot;Authorization&quot;, via[0].Header.Get(&quot;Authorization&quot;))
	return nil
}

huangapple
  • 本文由 发表于 2016年10月31日 16:29:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/40338711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定