github.com/aclisp/heapster@v0.19.2-0.20160613100040-51756f899a96/Godeps/_workspace/src/golang.org/x/oauth2/internal/token.go (about) 1 // Copyright 2014 The oauth2 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 internal contains support packages for oauth2 package. 6 package internal 7 8 import ( 9 "encoding/json" 10 "fmt" 11 "io" 12 "io/ioutil" 13 "mime" 14 "net/http" 15 "net/url" 16 "strconv" 17 "strings" 18 "time" 19 20 "golang.org/x/net/context" 21 ) 22 23 // Token represents the crendentials used to authorize 24 // the requests to access protected resources on the OAuth 2.0 25 // provider's backend. 26 // 27 // This type is a mirror of oauth2.Token and exists to break 28 // an otherwise-circular dependency. Other internal packages 29 // should convert this Token into an oauth2.Token before use. 30 type Token struct { 31 // AccessToken is the token that authorizes and authenticates 32 // the requests. 33 AccessToken string 34 35 // TokenType is the type of token. 36 // The Type method returns either this or "Bearer", the default. 37 TokenType string 38 39 // RefreshToken is a token that's used by the application 40 // (as opposed to the user) to refresh the access token 41 // if it expires. 42 RefreshToken string 43 44 // Expiry is the optional expiration time of the access token. 45 // 46 // If zero, TokenSource implementations will reuse the same 47 // token forever and RefreshToken or equivalent 48 // mechanisms for that TokenSource will not be used. 49 Expiry time.Time 50 51 // Raw optionally contains extra metadata from the server 52 // when updating a token. 53 Raw interface{} 54 } 55 56 // tokenJSON is the struct representing the HTTP response from OAuth2 57 // providers returning a token in JSON form. 58 type tokenJSON struct { 59 AccessToken string `json:"access_token"` 60 TokenType string `json:"token_type"` 61 RefreshToken string `json:"refresh_token"` 62 ExpiresIn expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number 63 Expires expirationTime `json:"expires"` // broken Facebook spelling of expires_in 64 } 65 66 func (e *tokenJSON) expiry() (t time.Time) { 67 if v := e.ExpiresIn; v != 0 { 68 return time.Now().Add(time.Duration(v) * time.Second) 69 } 70 if v := e.Expires; v != 0 { 71 return time.Now().Add(time.Duration(v) * time.Second) 72 } 73 return 74 } 75 76 type expirationTime int32 77 78 func (e *expirationTime) UnmarshalJSON(b []byte) error { 79 var n json.Number 80 err := json.Unmarshal(b, &n) 81 if err != nil { 82 return err 83 } 84 i, err := n.Int64() 85 if err != nil { 86 return err 87 } 88 *e = expirationTime(i) 89 return nil 90 } 91 92 var brokenAuthHeaderProviders = []string{ 93 "https://accounts.google.com/", 94 "https://www.googleapis.com/", 95 "https://github.com/", 96 "https://api.instagram.com/", 97 "https://www.douban.com/", 98 "https://api.dropbox.com/", 99 "https://api.soundcloud.com/", 100 "https://www.linkedin.com/", 101 "https://api.twitch.tv/", 102 "https://oauth.vk.com/", 103 "https://api.odnoklassniki.ru/", 104 "https://connect.stripe.com/", 105 "https://api.pushbullet.com/", 106 "https://oauth.sandbox.trainingpeaks.com/", 107 "https://oauth.trainingpeaks.com/", 108 "https://www.strava.com/oauth/", 109 "https://app.box.com/", 110 "https://test-sandbox.auth.corp.google.com", 111 "https://user.gini.net/", 112 } 113 114 // providerAuthHeaderWorks reports whether the OAuth2 server identified by the tokenURL 115 // implements the OAuth2 spec correctly 116 // See https://code.google.com/p/goauth2/issues/detail?id=31 for background. 117 // In summary: 118 // - Reddit only accepts client secret in the Authorization header 119 // - Dropbox accepts either it in URL param or Auth header, but not both. 120 // - Google only accepts URL param (not spec compliant?), not Auth header 121 // - Stripe only accepts client secret in Auth header with Bearer method, not Basic 122 func providerAuthHeaderWorks(tokenURL string) bool { 123 for _, s := range brokenAuthHeaderProviders { 124 if strings.HasPrefix(tokenURL, s) { 125 // Some sites fail to implement the OAuth2 spec fully. 126 return false 127 } 128 } 129 130 // Assume the provider implements the spec properly 131 // otherwise. We can add more exceptions as they're 132 // discovered. We will _not_ be adding configurable hooks 133 // to this package to let users select server bugs. 134 return true 135 } 136 137 func RetrieveToken(ctx context.Context, ClientID, ClientSecret, TokenURL string, v url.Values) (*Token, error) { 138 hc, err := ContextClient(ctx) 139 if err != nil { 140 return nil, err 141 } 142 v.Set("client_id", ClientID) 143 bustedAuth := !providerAuthHeaderWorks(TokenURL) 144 if bustedAuth && ClientSecret != "" { 145 v.Set("client_secret", ClientSecret) 146 } 147 req, err := http.NewRequest("POST", TokenURL, strings.NewReader(v.Encode())) 148 if err != nil { 149 return nil, err 150 } 151 req.Header.Set("Content-Type", "application/x-www-form-urlencoded") 152 if !bustedAuth { 153 req.SetBasicAuth(ClientID, ClientSecret) 154 } 155 r, err := hc.Do(req) 156 if err != nil { 157 return nil, err 158 } 159 defer r.Body.Close() 160 body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20)) 161 if err != nil { 162 return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) 163 } 164 if code := r.StatusCode; code < 200 || code > 299 { 165 return nil, fmt.Errorf("oauth2: cannot fetch token: %v\nResponse: %s", r.Status, body) 166 } 167 168 var token *Token 169 content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) 170 switch content { 171 case "application/x-www-form-urlencoded", "text/plain": 172 vals, err := url.ParseQuery(string(body)) 173 if err != nil { 174 return nil, err 175 } 176 token = &Token{ 177 AccessToken: vals.Get("access_token"), 178 TokenType: vals.Get("token_type"), 179 RefreshToken: vals.Get("refresh_token"), 180 Raw: vals, 181 } 182 e := vals.Get("expires_in") 183 if e == "" { 184 // TODO(jbd): Facebook's OAuth2 implementation is broken and 185 // returns expires_in field in expires. Remove the fallback to expires, 186 // when Facebook fixes their implementation. 187 e = vals.Get("expires") 188 } 189 expires, _ := strconv.Atoi(e) 190 if expires != 0 { 191 token.Expiry = time.Now().Add(time.Duration(expires) * time.Second) 192 } 193 default: 194 var tj tokenJSON 195 if err = json.Unmarshal(body, &tj); err != nil { 196 return nil, err 197 } 198 token = &Token{ 199 AccessToken: tj.AccessToken, 200 TokenType: tj.TokenType, 201 RefreshToken: tj.RefreshToken, 202 Expiry: tj.expiry(), 203 Raw: make(map[string]interface{}), 204 } 205 json.Unmarshal(body, &token.Raw) // no error checks for optional fields 206 } 207 // Don't overwrite `RefreshToken` with an empty value 208 // if this was a token refreshing request. 209 if token.RefreshToken == "" { 210 token.RefreshToken = v.Get("refresh_token") 211 } 212 return token, nil 213 }