This library is used to bypass golang oauth2 package token source limitations: golang/oauth2#262
The aim ot this library is to implement only the smallest possible subset of functionality for context support. It will reuse original library as match as possible. This goal is achieved through these steps:
- Reuse basic token retrieval by adopting existing data types, which implement
Oauth2TokenConfigandOauth2TokenSourceWithContext. Seeconvert.go - Reusing high-level functions by retrieving Token through context-aware
TokenSourceand passing it to the existing implementation with the help ofoauth2.StaticTokenSourc. Seetransport.goandgrpc/credentials.go - Reimplement only a small subset like
ReuseTokenSourceortokenRefresher, which is focused and bug-free.
All configuration is provided with the option pattern (no more context.WithValue mess).
All functions, provided in this library, should be familiar to oauth2 users. If something is missing - feel free to open an issue or make a PR. I believe, that everything can be adopted by this approach. The library is already used in production.
// grpc
package main
import (
"golang.org/x/oauth2"
"google.golang.org/grpc/credentials"
gcred "google.golang.org/grpc/credentials/google"
"github.com/TelpeNight/oauthctx"
grpcctx "github.com/TelpeNight/oauthctx/grpc"
)
var conf = oauthctx.NewConfig(&oauth2.Config{
//...
})
var refreshToken string = "..."
ts := conf.TokenSource(
&oauth2.Token{RefreshToken: refreshToken},
// custom http.Client can be provided with option
oauthctx.TokenSourceWithClient(...))
ts = oauthctx.ReuseTokenSource(nil, ts)
var bundle credentials.Bundle = gcred.NewDefaultCredentialsWithOptions(
gcred.DefaultCredentialsOptions{
PerRPCCreds: &grpcctx.TokenSource{
TokenSource: ts,
},
},
)
// use bundle to create a client. methods' context will be passed to oauth2, so overall call will respect timeouts