将自定义标头添加到OAuth令牌请求

时间:2020-01-17 18:53:27

标签: go oauth clientcredential

我正在使用Go客户端从Oracle Access Manager(OAM)获取令牌。 OAM在令牌请求上需要一个自定义标头,我使用以下代码添加了该标头。标头不应添加到使用检索到的令牌发出的请求中,

但是,我的解决方案有点像hack。我想知道是否有更好的方法。

package main

import (
    "bytes"
    "golang.org/x/net/context"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/clientcredentials"
    "net/http"
    "net/http/httputil"
)

type transport struct{}

var tokenPath = "/token"

func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
    // Modify the request here.
    if req.URL.Path == tokenPath {
        req.Header.Add("X-OAUTH-IDENTITY-DOMAIN-NAME", "DomainName")
    }

    reqBytes, err := httputil.DumpRequestOut(req, true)
    if err != nil {
        println(err)
    }

    println(string(reqBytes))
    println()

    response, e := http.DefaultTransport.RoundTrip(req)
    respBytes, _ := httputil.DumpResponse(response, true)
    println(string(respBytes))
    println()

    return response, e
}

func main(){
    hc := &http.Client{Transport: &transport{}}
    ctx := context.WithValue(context.Background(), oauth2.HTTPClient, hc)


    config := clientcredentials.Config{
        ClientID: "user",
        ClientSecret: "secret",
        TokenURL: "http://localhost:8080" + tokenPath,
        AuthStyle: oauth2.AuthStyleInHeader,
        Scopes: []string{"openid"},
    }

    client := config.Client(ctx)

    b := []byte(`{"Payload": {"Date": {"patientID": "1234","serviceDate": "2019-07-31T00:00:00",}}}`)
    reader := bytes.NewBuffer(b)

    resp, err := client.Post("http://localhost:8080/IsEligible", "application/json", reader )
    if err != nil{
        panic(err)
    }
    // do something with resp
    print(resp)
} 

0 个答案:

没有答案