2014-05-17 19:26:57 +04:00
|
|
|
// Copyright 2014 The oauth2 Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
2014-05-13 22:06:46 +04:00
|
|
|
|
2014-05-06 01:54:23 +04:00
|
|
|
// Package oauth2 provides support for making
|
|
|
|
// OAuth2 authorized and authenticated HTTP requests.
|
|
|
|
// It can additionally grant authorization with Bearer JWT.
|
|
|
|
package oauth2
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
2014-09-05 09:43:23 +04:00
|
|
|
"fmt"
|
2014-05-06 01:54:23 +04:00
|
|
|
"io/ioutil"
|
|
|
|
"mime"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2014-08-13 06:50:34 +04:00
|
|
|
"strconv"
|
2014-05-06 01:54:23 +04:00
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type tokenRespBody struct {
|
2014-08-13 06:50:34 +04:00
|
|
|
AccessToken string `json:"access_token"`
|
|
|
|
TokenType string `json:"token_type"`
|
|
|
|
RefreshToken string `json:"refresh_token"`
|
|
|
|
ExpiresIn int64 `json:"expires_in"` // in seconds
|
|
|
|
IdToken string `json:"id_token"`
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
|
2014-05-10 11:41:39 +04:00
|
|
|
// TokenFetcher refreshes or fetches a new access token from the
|
2014-05-06 01:54:23 +04:00
|
|
|
// provider. It should return an error if it's not capable of
|
|
|
|
// retrieving a token.
|
2014-05-10 11:41:39 +04:00
|
|
|
type TokenFetcher interface {
|
|
|
|
// FetchToken retrieves a new access token for the provider.
|
2014-05-06 01:54:23 +04:00
|
|
|
// If the implementation doesn't know how to retrieve a new token,
|
2014-08-14 09:22:35 +04:00
|
|
|
// it returns an error. The existing token may be nil.
|
2014-05-10 11:41:39 +04:00
|
|
|
FetchToken(existing *Token) (*Token, error)
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Options represents options to provide OAuth 2.0 client credentials
|
|
|
|
// and access level. A sample configuration:
|
|
|
|
type Options struct {
|
|
|
|
// ClientID is the OAuth client identifier used when communicating with
|
|
|
|
// the configured OAuth provider.
|
|
|
|
ClientID string `json:"client_id"`
|
|
|
|
|
|
|
|
// ClientSecret is the OAuth client secret used when communicating with
|
|
|
|
// the configured OAuth provider.
|
|
|
|
ClientSecret string `json:"client_secret"`
|
|
|
|
|
|
|
|
// RedirectURL is the URL to which the user will be returned after
|
|
|
|
// granting (or denying) access.
|
|
|
|
RedirectURL string `json:"redirect_url"`
|
|
|
|
|
2014-08-14 00:40:18 +04:00
|
|
|
// Scopes optionally specifies a list of requested permission scopes.
|
|
|
|
Scopes []string `json:"scopes,omitempty"`
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewConfig creates a generic OAuth 2.0 configuration that talks
|
|
|
|
// to an OAuth 2.0 provider specified with authURL and tokenURL.
|
2014-07-21 08:07:57 +04:00
|
|
|
func NewConfig(opts *Options, authURL, tokenURL string) (*Config, error) {
|
2014-07-21 08:08:11 +04:00
|
|
|
aURL, err := url.Parse(authURL)
|
|
|
|
if err != nil {
|
2014-07-21 08:07:57 +04:00
|
|
|
return nil, err
|
2014-07-21 03:56:38 +04:00
|
|
|
}
|
2014-07-21 08:08:11 +04:00
|
|
|
tURL, err := url.Parse(tokenURL)
|
|
|
|
if err != nil {
|
2014-07-21 08:07:57 +04:00
|
|
|
return nil, err
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
2014-09-04 23:03:06 +04:00
|
|
|
if opts.ClientID == "" {
|
|
|
|
return nil, errors.New("oauth2: missing client ID")
|
|
|
|
}
|
|
|
|
return &Config{
|
2014-09-04 22:58:14 +04:00
|
|
|
opts: opts,
|
|
|
|
authURL: aURL,
|
|
|
|
tokenURL: tURL,
|
2014-09-04 23:03:06 +04:00
|
|
|
}, nil
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
|
2014-05-10 15:16:50 +04:00
|
|
|
// Config represents the configuration of an OAuth 2.0 consumer client.
|
|
|
|
type Config struct {
|
2014-09-01 02:36:50 +04:00
|
|
|
// Client is the HTTP client to be used to retrieve
|
2014-09-01 02:13:59 +04:00
|
|
|
// tokens from the OAuth 2.0 provider.
|
|
|
|
Client *http.Client
|
|
|
|
|
2014-09-03 01:06:51 +04:00
|
|
|
// Transport is the http.RoundTripper to be used
|
2014-09-01 02:36:50 +04:00
|
|
|
// to construct new oauth2.Transport instances from
|
2014-09-01 02:13:59 +04:00
|
|
|
// this configuration.
|
|
|
|
Transport http.RoundTripper
|
|
|
|
|
2014-05-06 01:54:23 +04:00
|
|
|
opts *Options
|
|
|
|
// AuthURL is the URL the user will be directed to
|
|
|
|
// in order to grant access.
|
2014-07-21 03:56:38 +04:00
|
|
|
authURL *url.URL
|
2014-05-06 01:54:23 +04:00
|
|
|
// TokenURL is the URL used to retrieve OAuth tokens.
|
2014-07-21 03:56:38 +04:00
|
|
|
tokenURL *url.URL
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// AuthCodeURL returns a URL to OAuth 2.0 provider's consent page
|
|
|
|
// that asks for permissions for the required scopes explicitly.
|
2014-09-05 09:43:23 +04:00
|
|
|
//
|
|
|
|
// State is a token to protect the user from CSRF attacks. You must
|
|
|
|
// always provide a non-zero string and validate that it matches the
|
|
|
|
// the state query parameter on your redirect callback.
|
|
|
|
// See http://tools.ietf.org/html/rfc6749#section-10.12 for more info.
|
|
|
|
//
|
|
|
|
// Access type is an OAuth extension that gets sent as the
|
|
|
|
// "access_type" field in the URL from AuthCodeURL.
|
|
|
|
// It may be "online" (default) or "offline".
|
|
|
|
// If your application needs to refresh access tokens when the
|
|
|
|
// user is not present at the browser, then use offline. This
|
|
|
|
// will result in your application obtaining a refresh token
|
|
|
|
// the first time your application exchanges an authorization
|
|
|
|
// code for a user.
|
|
|
|
//
|
|
|
|
// Approval prompt indicates whether the user should be
|
|
|
|
// re-prompted for consent. If set to "auto" (default) the
|
|
|
|
// user will be prompted only if they haven't previously
|
|
|
|
// granted consent and the code can only be exchanged for an
|
|
|
|
// access token. If set to "force" the user will always be prompted,
|
|
|
|
// and the code can be exchanged for a refresh token.
|
|
|
|
func (c *Config) AuthCodeURL(state, accessType, prompt string) (authURL string) {
|
2014-07-21 08:08:11 +04:00
|
|
|
u := *c.authURL
|
2014-09-05 00:28:18 +04:00
|
|
|
v := url.Values{
|
|
|
|
"response_type": {"code"},
|
|
|
|
"client_id": {c.opts.ClientID},
|
|
|
|
"redirect_uri": condVal(c.opts.RedirectURL),
|
|
|
|
"scope": condVal(strings.Join(c.opts.Scopes, " ")),
|
|
|
|
"state": condVal(state),
|
2014-09-05 09:43:23 +04:00
|
|
|
"access_type": condVal(accessType),
|
|
|
|
"approval_prompt": condVal(prompt),
|
2014-07-29 23:39:33 +04:00
|
|
|
}
|
2014-09-05 00:28:18 +04:00
|
|
|
q := v.Encode()
|
2014-05-06 01:54:23 +04:00
|
|
|
if u.RawQuery == "" {
|
|
|
|
u.RawQuery = q
|
|
|
|
} else {
|
|
|
|
u.RawQuery += "&" + q
|
|
|
|
}
|
2014-07-21 03:56:38 +04:00
|
|
|
return u.String()
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewTransport creates a new authorizable transport. It doesn't
|
|
|
|
// initialize the new transport with a token, so after creation,
|
|
|
|
// you need to set a valid token (or an expired token with a valid
|
|
|
|
// refresh token) in order to be able to do authorized requests.
|
2014-08-14 09:22:35 +04:00
|
|
|
func (c *Config) NewTransport() *Transport {
|
2014-09-03 01:06:51 +04:00
|
|
|
return NewTransport(c.transport(), c, nil)
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
|
2014-08-17 06:29:11 +04:00
|
|
|
// NewTransportWithCode exchanges the OAuth 2.0 authorization code with
|
2014-05-06 01:54:23 +04:00
|
|
|
// the provider to fetch a new access token (and refresh token). Once
|
2014-10-04 10:15:35 +04:00
|
|
|
// it successfully retrieves a new token, creates a new transport
|
2014-05-06 01:54:23 +04:00
|
|
|
// authorized with it.
|
2014-08-17 06:29:11 +04:00
|
|
|
func (c *Config) NewTransportWithCode(code string) (*Transport, error) {
|
|
|
|
token, err := c.Exchange(code)
|
2014-05-06 01:54:23 +04:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2014-09-03 01:06:51 +04:00
|
|
|
return NewTransport(c.transport(), c, token), nil
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
|
2014-05-10 11:41:39 +04:00
|
|
|
// FetchToken retrieves a new access token and updates the existing token
|
2014-05-06 01:54:23 +04:00
|
|
|
// with the newly fetched credentials. If existing token doesn't
|
|
|
|
// contain a refresh token, it returns an error.
|
2014-05-10 15:16:50 +04:00
|
|
|
func (c *Config) FetchToken(existing *Token) (*Token, error) {
|
2014-05-06 01:54:23 +04:00
|
|
|
if existing == nil || existing.RefreshToken == "" {
|
2014-09-05 00:33:06 +04:00
|
|
|
return nil, errors.New("oauth2: cannot fetch access token without refresh token")
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
2014-08-14 03:47:57 +04:00
|
|
|
return c.retrieveToken(url.Values{
|
2014-05-06 01:54:23 +04:00
|
|
|
"grant_type": {"refresh_token"},
|
|
|
|
"refresh_token": {existing.RefreshToken},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2014-08-17 06:29:11 +04:00
|
|
|
// Exchange exchanges the authorization code with the OAuth 2.0 provider
|
2014-06-27 04:27:53 +04:00
|
|
|
// to retrieve a new access token.
|
2014-08-17 06:29:11 +04:00
|
|
|
func (c *Config) Exchange(code string) (*Token, error) {
|
2014-09-05 00:28:18 +04:00
|
|
|
return c.retrieveToken(url.Values{
|
|
|
|
"grant_type": {"authorization_code"},
|
|
|
|
"code": {code},
|
|
|
|
"redirect_uri": condVal(c.opts.RedirectURL),
|
|
|
|
"scope": condVal(strings.Join(c.opts.Scopes, " ")),
|
|
|
|
})
|
2014-06-27 04:27:53 +04:00
|
|
|
}
|
|
|
|
|
2014-08-14 03:47:57 +04:00
|
|
|
func (c *Config) retrieveToken(v url.Values) (*Token, error) {
|
2014-05-06 01:54:23 +04:00
|
|
|
v.Set("client_id", c.opts.ClientID)
|
2014-09-05 00:28:18 +04:00
|
|
|
bustedAuth := !providerAuthHeaderWorks(c.tokenURL.String())
|
|
|
|
if bustedAuth && c.opts.ClientSecret != "" {
|
|
|
|
v.Set("client_secret", c.opts.ClientSecret)
|
|
|
|
}
|
|
|
|
req, err := http.NewRequest("POST", c.tokenURL.String(), strings.NewReader(v.Encode()))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
|
|
if !bustedAuth && c.opts.ClientSecret != "" {
|
|
|
|
req.SetBasicAuth(c.opts.ClientID, c.opts.ClientSecret)
|
|
|
|
}
|
|
|
|
r, err := c.client().Do(req)
|
2014-05-06 01:54:23 +04:00
|
|
|
if err != nil {
|
2014-08-14 03:47:57 +04:00
|
|
|
return nil, err
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
defer r.Body.Close()
|
2014-09-05 09:43:23 +04:00
|
|
|
body, err := ioutil.ReadAll(r.Body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
|
|
|
|
}
|
|
|
|
if c := r.StatusCode; c < 200 || c > 299 {
|
|
|
|
return nil, fmt.Errorf("oauth2: cannot fetch token: %v\nResponse: %s", r.Status, body)
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
resp := &tokenRespBody{}
|
|
|
|
content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
|
|
|
switch content {
|
|
|
|
case "application/x-www-form-urlencoded", "text/plain":
|
|
|
|
vals, err := url.ParseQuery(string(body))
|
|
|
|
if err != nil {
|
2014-08-14 03:47:57 +04:00
|
|
|
return nil, err
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
resp.AccessToken = vals.Get("access_token")
|
|
|
|
resp.TokenType = vals.Get("token_type")
|
|
|
|
resp.RefreshToken = vals.Get("refresh_token")
|
2014-08-13 06:50:34 +04:00
|
|
|
resp.ExpiresIn, _ = strconv.ParseInt(vals.Get("expires_in"), 10, 64)
|
2014-05-06 01:54:23 +04:00
|
|
|
resp.IdToken = vals.Get("id_token")
|
|
|
|
default:
|
2014-09-07 03:39:43 +04:00
|
|
|
if err = json.Unmarshal(body, &resp); err != nil {
|
2014-08-14 03:47:57 +04:00
|
|
|
return nil, err
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
}
|
2014-08-14 03:47:57 +04:00
|
|
|
token := &Token{
|
|
|
|
AccessToken: resp.AccessToken,
|
|
|
|
TokenType: resp.TokenType,
|
|
|
|
RefreshToken: resp.RefreshToken,
|
|
|
|
}
|
2014-05-06 01:54:23 +04:00
|
|
|
// Don't overwrite `RefreshToken` with an empty value
|
2014-08-14 03:47:57 +04:00
|
|
|
// if this was a token refreshing request.
|
|
|
|
if resp.RefreshToken == "" {
|
|
|
|
token.RefreshToken = v.Get("refresh_token")
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
if resp.ExpiresIn == 0 {
|
2014-08-14 03:47:57 +04:00
|
|
|
token.Expiry = time.Time{}
|
2014-05-06 01:54:23 +04:00
|
|
|
} else {
|
2014-08-14 03:47:57 +04:00
|
|
|
token.Expiry = time.Now().Add(time.Duration(resp.ExpiresIn) * time.Second)
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
|
|
|
if resp.IdToken != "" {
|
2014-08-14 03:47:57 +04:00
|
|
|
if token.Extra == nil {
|
|
|
|
token.Extra = make(map[string]string)
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
2014-08-14 03:47:57 +04:00
|
|
|
token.Extra["id_token"] = resp.IdToken
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
2014-08-14 03:47:57 +04:00
|
|
|
return token, nil
|
2014-05-06 01:54:23 +04:00
|
|
|
}
|
2014-09-03 01:06:51 +04:00
|
|
|
|
|
|
|
func (c *Config) transport() http.RoundTripper {
|
|
|
|
if c.Transport != nil {
|
|
|
|
return c.Transport
|
|
|
|
}
|
|
|
|
return http.DefaultTransport
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Config) client() *http.Client {
|
|
|
|
if c.Client != nil {
|
|
|
|
return c.Client
|
|
|
|
}
|
|
|
|
return http.DefaultClient
|
|
|
|
}
|
2014-09-05 00:28:18 +04:00
|
|
|
|
|
|
|
func condVal(v string) []string {
|
|
|
|
if v == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return []string{v}
|
|
|
|
}
|
|
|
|
|
|
|
|
// providerAuthHeaderWorks reports whether the OAuth2 server identified by the tokenURL
|
|
|
|
// implements the OAuth2 spec correctly
|
|
|
|
// See https://code.google.com/p/goauth2/issues/detail?id=31 for background.
|
|
|
|
// In summary:
|
|
|
|
// - Reddit only accepts client secret in the Authorization header
|
|
|
|
// - Dropbox accepts either it in URL param or Auth header, but not both.
|
|
|
|
// - Google only accepts URL param (not spec compliant?), not Auth header
|
|
|
|
func providerAuthHeaderWorks(tokenURL string) bool {
|
|
|
|
if strings.HasPrefix(tokenURL, "https://accounts.google.com/") ||
|
|
|
|
strings.HasPrefix(tokenURL, "https://github.com/") ||
|
|
|
|
strings.HasPrefix(tokenURL, "https://api.instagram.com/") ||
|
2014-09-07 21:05:03 +04:00
|
|
|
strings.HasPrefix(tokenURL, "https://www.douban.com/") ||
|
2014-09-11 06:49:49 +04:00
|
|
|
strings.HasPrefix(tokenURL, "https://api.dropbox.com/") ||
|
|
|
|
strings.HasPrefix(tokenURL, "https://www.linkedin.com/") {
|
2014-09-05 00:28:18 +04:00
|
|
|
// Some sites fail to implement the OAuth2 spec fully.
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Assume the provider implements the spec properly
|
|
|
|
// otherwise. We can add more exceptions as they're
|
|
|
|
// discovered. We will _not_ be adding configurable hooks
|
|
|
|
// to this package to let users select server bugs.
|
|
|
|
return true
|
|
|
|
}
|