无法在Golang中的GET请求的标头中传递不记名令牌 [英] Not able to pass Bearer token in headers of a GET request in Golang

查看:408
本文介绍了无法在Golang中的GET请求的标头中传递不记名令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用oauth2来访问第三方API。我可以获取访问令牌,但是当我尝试通过在请求头中传递不记名令牌来调用API时,它会给我401(未授权)错误。虽然当我尝试通过POSTMAN传递标头(Authorization:Bearer)来实现时效果很好。但是它并不适用go。



以下是代码示例。

  url:=http://api.kounta.com/v1/companies/me.json

var bearer =持票人+< ACCESS TOKEN HERE>
req,err:= http.NewRequest(GET,url,nil)
req.Header.Add(授权,持票人)

客户端:= urlfetch。客户端(上下文)

resp,err:= client.Do(req)
if err!= nil {
panic(err)
}
defer resp.Body.Close()

ody,_:= ioutil.ReadAll(resp.Body)
writer.Write([] byte(body))//给出401 Unauthorized错误,虽然同样的工作使用POSTMAN


解决方案

问题。实际上这个问题是双向的。

1)API端点做了一个重定向(302),这导致了302响应,然后另一个API被调用。



2)GO默认不转发标题,因此我的不记名令牌在中间丢失。



FIX:

我必须重写客户端的CheckRedirect函数并手动将标题传递给新请求。

  client.CheckRedirect = checkRedirectFunc 

以下是我

  func checkRedirectFunc(req * http.Request,via [] * http.Request)error {
req.Header.Add(Authorization,via [0] .Header.Get(Authorization))
return nil
}
pre>

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

解决方案

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
}

这篇关于无法在Golang中的GET请求的标头中传递不记名令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆