shurcooL / graphql

Package graphql provides a GraphQL client implementation.
MIT License
709 stars 282 forks source link

OAuth2 Bearer Token with Customer HttpClient #77

Open shanhui1 opened 3 years ago

shanhui1 commented 3 years ago

For our use case, we need to pass in our custom HttpClient and make request with a different OAuth2 Bearer Token. We can't use the oauth2 lib as suggested. Anyway to get access to the req.headers before sending mutation queries?

I have a custom HttpClient such as this:

type AddHeaderTransport struct {
    T http.RoundTripper
}

func (adt *AddHeaderTransport) RoundTrip(req *http.Request) (*http.Response, error) {
    // TODO: bearer_token needs to be changed in each request cycle as there are many accounts that need to be called
        req.Header.Add("Authorization", "Bearer token_here")
    req.Header.Add("User-Agent", "go")
    return adt.T.RoundTrip(req)
}

func NewAddHeaderTransport(T http.RoundTripper) *AddHeaderTransport {
    if T == nil {
        T = http.DefaultTransport
    }
    return &AddHeaderTransport{T}
}

func NewClientWithAccessToken(timeout, tcpConnTimeout, tlsConnTimeout time.Duration) *http.Client {
    transport := &http.Transport{
        DialContext: (&net.Dialer{
            Timeout: tcpConnTimeout,
        }).DialContext,
        TLSHandshakeTimeout: tlsConnTimeout,
    }
    cc := http.Client{
        Transport: NewAddHeaderTransport(transport),
        Timeout:   timeout,
    }
    return &cc
}

func DefaultClientWithAccessToken() *http.Client {
    return NewClientWithAccessToken(
        DEFAULT_TIMEOUT_MS*time.Millisecond,
        DEFAULT_CONNECTION_TIMEOUT_MS*time.Millisecond,
        DEFAULT_CONNECTION_TIMEOUT_MS*time.Millisecond,
    )
}
onurkose commented 2 years ago

I was looking for a solution to make self signed certificates work for local development. But I believe this will solve your problem too.

tr := &http.Transport{
    TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
sslcli := &http.Client{Transport: tr}
ctx := context.TODO()
ctx = context.WithValue(ctx, oauth2.HTTPClient, sslcli)
src := oauth2.StaticTokenSource(
    &oauth2.Token{AccessToken: "...put your token without the Bearer prefix here..."},
)