authhandler.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2021 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package authhandler implements a TokenSource to support
  5. // "three-legged OAuth 2.0" via a custom AuthorizationHandler.
  6. package authhandler
  7. import (
  8. "context"
  9. "errors"
  10. "golang.org/x/oauth2"
  11. )
  12. // AuthorizationHandler is a 3-legged-OAuth helper that prompts
  13. // the user for OAuth consent at the specified auth code URL
  14. // and returns an auth code and state upon approval.
  15. type AuthorizationHandler func(authCodeURL string) (code string, state string, err error)
  16. // TokenSource returns an oauth2.TokenSource that fetches access tokens
  17. // using 3-legged-OAuth flow.
  18. //
  19. // The provided context.Context is used for oauth2 Exchange operation.
  20. //
  21. // The provided oauth2.Config should be a full configuration containing AuthURL,
  22. // TokenURL, and Scope.
  23. //
  24. // An environment-specific AuthorizationHandler is used to obtain user consent.
  25. //
  26. // Per the OAuth protocol, a unique "state" string should be specified here.
  27. // This token source will verify that the "state" is identical in the request
  28. // and response before exchanging the auth code for OAuth token to prevent CSRF
  29. // attacks.
  30. func TokenSource(ctx context.Context, config *oauth2.Config, state string, authHandler AuthorizationHandler) oauth2.TokenSource {
  31. return oauth2.ReuseTokenSource(nil, authHandlerSource{config: config, ctx: ctx, authHandler: authHandler, state: state})
  32. }
  33. type authHandlerSource struct {
  34. ctx context.Context
  35. config *oauth2.Config
  36. authHandler AuthorizationHandler
  37. state string
  38. }
  39. func (source authHandlerSource) Token() (*oauth2.Token, error) {
  40. url := source.config.AuthCodeURL(source.state)
  41. code, state, err := source.authHandler(url)
  42. if err != nil {
  43. return nil, err
  44. }
  45. if state != source.state {
  46. return nil, errors.New("state mismatch in 3-legged-OAuth flow")
  47. }
  48. return source.config.Exchange(source.ctx, code)
  49. }