Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OAuth2 Bearer Token with Customer HttpClient #77

Open
shanhui1 opened this issue Oct 13, 2021 · 1 comment
Open

OAuth2 Bearer Token with Customer HttpClient #77

shanhui1 opened this issue Oct 13, 2021 · 1 comment

Comments

@shanhui1
Copy link

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
Copy link

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..."},
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants