Skip to content

Instantly share code, notes, and snippets.

@agtorre
Last active December 26, 2019 12:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save agtorre/350c5b4ce0ccebc5ac0f to your computer and use it in GitHub Desktop.
Save agtorre/350c5b4ce0ccebc5ac0f to your computer and use it in GitHub Desktop.
Store OAuth2 Token Using Redis
type Config struct {
*oauth2.Config
Redis MyRedisInterface
}
func (c *Config) StoreToken(token *oauth2.Token) error {
//store the token in redis here using c.Redis
}
func (c *Config) Exchange(ctx context.Context, code string) (*oauth2.Token, error) {
token, err := c.Config.Exchange(ctx, code)
if err != nil {
return nil, err
}
if err := c.StoreToken(token); err != nil {
return nil, err
}
return token, nil
}
func (c *Config) Client(ctx context.Context, t *Token) *http.Client {
return oauth2.NewClient(ctx, c.TokenSource(ctx, t))
}
func (c *Config) TokenSource(ctx context.Context, t *oauth2.Token) oauth2.TokenSource {
rts := &RedisTokenSource{
source: c.Config.TokenSource(ctx, t),
config: c,
}
return oauth2.ReuseTokenSource(t, rts)
}
type RedisTokenSource struct {
source oauth2.TokenSource
config *Config
}
func (t *RedisTokenSource) Token() (*oauth2.Token, error) {
token, err := t.source.Token()
if err != nil{
return nil, err
}
if err := t.config.StoreToken(token); err != nil {
return nil, err
}
return token, nil
}
@agtorre
Copy link
Author

agtorre commented Dec 26, 2015

Usage:

c := Config{
  Config: MyNormalOAuth2Config,
  Redis: MyRedisStruct,
}

// use client to Get/Post/Whatever!
client := c.Client(oauth2.NoContext, nil)

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