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