oauth2.0 在KrakenD中使用自定义Http处理程序(Go插件)时出现401未授权错误

0pizxfdo  于 2022-11-21  发布在  Go
关注(0)|答案(1)|浏览(170)

我试图通过使用go lang在KrakenD中添加自定义逻辑来构建http插件。但目前我从KrakenD中得到500内部服务器错误和后端中的401未授权错误。当我调试更多时,我可以看到不记名令牌没有传递到后端。
KrakenD后端配置:

"backend": [
        {
            "url_pattern":  "My downstream Path",
            "method":  "Http Method",
            "host": [
                 "My Host"
            ],
            "extra_config": {
                "github.com/devopsfaith/krakend/transport/http/client/executor": {
                    "name": "Plugin Register Name"
                },
                "github.com/devopsfaith/krakend-oauth2-clientcredentials": {
                    "endpoint_params": {},
                    "token_url": "My Token URL",
                    "client_id": "My Client ID",
                    "client_secret": "My Client Secret"
                }
            },
            "disable_host_sanitize": false
        }
]

Go Lang插件

func (r registerer) registerClients(ctx context.Context, extra map[string]interface{}) (http.Handler, error) {
    name, ok := extra["name"].(string)
    if !ok {
        return nil, errors.New("wrong config")
    }
    if name != string(r) {
        return nil, fmt.Errorf("unknown register %s", name)
    }

    // return the actual handler wrapping or your custom logic so it can be used as a replacement for the default http client
    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {

        fmt.Println(req.Header.Get("Authorization")) // Bearer token is coming empty. I am expecting bearer token value here, which was configured in KrakenD

        client := &http.Client{
            Timeout: time.Second * 10,
        }
        resp, err := client.Do(req)
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        w.Write(body)
    }), nil
}
o2rvlv0m

o2rvlv0m1#

Your backend doesn't see Bearer token, because krakend by default doesn't forward this header. You must set input_headers field to your krakend config. Check link: https://www.krakend.io/docs/endpoints/parameter-forwarding/#headers-forwarding
Your config must be:

"input_headers": [
    "Authorization"
],
"backend": [
        {
            "url_pattern":  "My downstream Path",
            "method":  "Http Method",
            "host": [
                 "My Host"
            ],
            "extra_config": {
                "github.com/devopsfaith/krakend/transport/http/client/executor": {
                    "name": "Plugin Register Name"
                },
                "github.com/devopsfaith/krakend-oauth2-clientcredentials": {
                    "endpoint_params": {},
                    "token_url": "My Token URL",
                    "client_id": "My Client ID",
                    "client_secret": "My Client Secret"
                }
            },
            "disable_host_sanitize": false
        }
]

相关问题