Debian Codegraph @

oauth/oauth.go

raw symbols SCIP
1 // Copyright 2010 Gary Burd
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"): you may
4 // not use this file except in compliance with the License. You may obtain
5 // a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations
13 // under the License.
14
15 // Package oauth is consumer interface for OAuth 1.0, OAuth 1.0a and RFC 5849.
16 //
17 // Redirection-based Authorization
18 //
19 // This section outlines how to use the oauth package in redirection-based
20 // authorization (http://tools.ietf.org/html/rfc5849#section-2).
21 //
22 // Step 1: Create a Client using credentials and URIs provided by the server.
23 // The Client can be initialized once at application startup and stored in a
24 // package-level variable.
25 //
26 // Step 2: Request temporary credentials using the Client
27 // RequestTemporaryCredentials method. The callbackURL parameter is the URL of
28 // the callback handler in step 4. Save the returned credential secret so that
29 // it can be later found using credential token as a key. The secret can be
30 // stored in a database keyed by the token. Another option is to store the
31 // token and secret in session storage or a cookie.
32 //
33 // Step 3: Redirect the user to URL returned from AuthorizationURL method. The
34 // AuthorizationURL method uses the temporary credentials from step 2 and other
35 // parameters as specified by the server.
36 //
37 // Step 4: The server redirects back to the callback URL specified in step 2
38 // with the temporary token and a verifier. Use the temporary token to find the
39 // temporary secret saved in step 2. Using the temporary token, temporary
40 // secret and verifier, request token credentials using the client RequestToken
41 // method. Save the returned credentials for later use in the application.
42 //
43 // Signing Requests
44 //
45 // The Client type has two low-level methods for signing requests, SignForm and
46 // SetAuthorizationHeader.
47 //
48 // The SignForm method adds an OAuth signature to a form. The application makes
49 // an authenticated request by encoding the modified form to the query string
50 // or request body.
51 //
52 // The SetAuthorizationHeader method adds an OAuth siganture to a request
53 // header. The SetAuthorizationHeader method is the only way to correctly sign
54 // a request if the application sets the URL Opaque field when making a
55 // request.
56 //
57 // The Get, Put, Post and Delete methods sign and invoke a request using the
58 // supplied net/http Client. These methods are easy to use, but not as flexible
59 // as constructing a request using one of the low-level methods.
60 //
61 // Context With HTTP Client
62 //
63 // A context-enabled method can include a custom HTTP client in the
64 // context and execute an HTTP request using the included HTTP client.
65 //
66 // hc := &http.Client{Timeout: 2 * time.Second}
67 // ctx := context.WithValue(context.Background(), oauth.HTTPClient, hc)
68 // c := oauth.Client{ /* Any settings */ }
69 // resp, err := c.GetContext(ctx, &oauth.Credentials{}, rawurl, nil)
70 package oauth // import "github.com/gomodule/oauth1/oauth"
71
72 import (
73 "bytes"
74 "context"
75 "crypto"
76 "crypto/hmac"
77 "crypto/rand"
78 "crypto/rsa"
79 "crypto/sha1"
80 "encoding/base64"
81 "encoding/binary"
82 "errors"
83 "fmt"
84 "io"
85 "io/ioutil"
86 "net/http"
87 "net/url"
88 "sort"
89 "strconv"
90 "strings"
91 "sync/atomic"
92 "time"
93 )
94
95 // noscape[b] is true if b should not be escaped per section 3.6 of the RFC.
96 var noEscape = [256]bool{
97 'A': true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
98 'a': true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
99 '0': true, true, true, true, true, true, true, true, true, true,
100 '-': true,
101 '.': true,
102 '_': true,
103 '~': true,
104 }
105
106 // encode encodes string per section 3.6 of the RFC. If double is true, then
107 // the encoding is applied twice.
108 func encode(s string, double bool) []byte {
109 // Compute size of result.
110 m := 3
111 if double {
112 m = 5
113 }
114 n := 0
115 for i := 0; i < len(s); i++ {
116 if noEscape[s[i]] {
117 n++
118 } else {
119 n += m
120 }
121 }
122
123 p := make([]byte, n)
124
125 // Encode it.
126 j := 0
127 for i := 0; i < len(s); i++ {
128 b := s[i]
129 if noEscape[b] {
130 p[j] = b
131 j++
132 } else if double {
133 p[j] = '%'
134 p[j+1] = '2'
135 p[j+2] = '5'
136 p[j+3] = "0123456789ABCDEF"[b>>4]
137 p[j+4] = "0123456789ABCDEF"[b&15]
138 j += 5
139 } else {
140 p[j] = '%'
141 p[j+1] = "0123456789ABCDEF"[b>>4]
142 p[j+2] = "0123456789ABCDEF"[b&15]
143 j += 3
144 }
145 }
146 return p
147 }
148
149 type keyValue struct{ key, value []byte }
150
151 type byKeyValue []keyValue
152
153 func (p byKeyValue) Len() int { return len(p) }
154 func (p byKeyValue) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
155 func (p byKeyValue) Less(i, j int) bool {
156 sgn := bytes.Compare(p[i].key, p[j].key)
157 if sgn == 0 {
158 sgn = bytes.Compare(p[i].value, p[j].value)
159 }
160 return sgn < 0
161 }
162
163 func (p byKeyValue) appendValues(values url.Values) byKeyValue {
164 for k, vs := range values {
165 k := encode(k, true)
166 for _, v := range vs {
167 v := encode(v, true)
168 p = append(p, keyValue{k, v})
169 }
170 }
171 return p
172 }
173
174 // writeBaseString writes method, url, and params to w using the OAuth signature
175 // base string computation described in section 3.4.1 of the RFC.
176 func writeBaseString(w io.Writer, method string, u *url.URL, form url.Values, oauthParams map[string]string) {
177 // Method
178 w.Write(encode(strings.ToUpper(method), false))
179 w.Write([]byte{'&'})
180
181 // URL
182 scheme := strings.ToLower(u.Scheme)
183 host := strings.ToLower(u.Host)
184
185 uNoQuery := *u
186 uNoQuery.RawQuery = ""
187 path := uNoQuery.RequestURI()
188
189 switch {
190 case scheme == "http" && strings.HasSuffix(host, ":80"):
191 host = host[:len(host)-len(":80")]
192 case scheme == "https" && strings.HasSuffix(host, ":443"):
193 host = host[:len(host)-len(":443")]
194 }
195
196 w.Write(encode(scheme, false))
197 w.Write(encode("://", false))
198 w.Write(encode(host, false))
199 w.Write(encode(path, false))
200 w.Write([]byte{'&'})
201
202 // Create sorted slice of encoded parameters. Parameter keys and values are
203 // double encoded in a single step. This is safe because double encoding
204 // does not change the sort order.
205 queryParams := u.Query()
206 p := make(byKeyValue, 0, len(form)+len(queryParams)+len(oauthParams))
207 p = p.appendValues(form)
208 p = p.appendValues(queryParams)
209 for k, v := range oauthParams {
210 p = append(p, keyValue{encode(k, true), encode(v, true)})
211 }
212 sort.Sort(p)
213
214 // Write the parameters.
215 encodedAmp := encode("&", false)
216 encodedEqual := encode("=", false)
217 sep := false
218 for _, kv := range p {
219 if sep {
220 w.Write(encodedAmp)
221 } else {
222 sep = true
223 }
224 w.Write(kv.key)
225 w.Write(encodedEqual)
226 w.Write(kv.value)
227 }
228 }
229
230 var nonceCounter uint64
231
232 func init() {
233 if err := binary.Read(rand.Reader, binary.BigEndian, &nonceCounter); err != nil {
234 // fallback to time if rand reader is broken
235 nonceCounter = uint64(time.Now().UnixNano())
236 }
237 }
238
239 // nonce returns a unique string.
240 func nonce() string {
241 return strconv.FormatUint(atomic.AddUint64(&nonceCounter, 1), 16)
242 }
243
244 // SignatureMethod identifies a signature method.
245 type SignatureMethod int
246
247 func (sm SignatureMethod) String() string {
248 switch sm {
249 case RSASHA1:
250 return "RSA-SHA1"
251 case HMACSHA1:
252 return "HMAC-SHA1"
253 case PLAINTEXT:
254 return "PLAINTEXT"
255 default:
256 return "unknown"
257 }
258 }
259
260 const (
261 HMACSHA1 SignatureMethod = iota // HMAC-SHA1
262 RSASHA1 // RSA-SHA1
263 PLAINTEXT // Plain text
264 )
265
266 // Credentials represents client, temporary and token credentials.
267 type Credentials struct {
268 Token string // Also known as consumer key or access token.
269 Secret string // Also known as consumer secret or access token secret.
270 }
271
272 // Client represents an OAuth client.
273 type Client struct {
274 // Credentials specifies the client key and secret.
275 // Also known as the consumer key and secret
276 Credentials Credentials
277
278 // TemporaryCredentialRequestURI is the endpoint used by the client to
279 // obtain a set of temporary credentials. Also known as the request token
280 // URL.
281 TemporaryCredentialRequestURI string
282
283 // ResourceOwnerAuthorizationURI is the endpoint to which the resource
284 // owner is redirected to grant authorization. Also known as authorization
285 // URL.
286 ResourceOwnerAuthorizationURI string
287
288 // TokenRequestURI is the endpoint used by the client to request a set of
289 // token credentials using a set of temporary credentials. Also known as
290 // access token URL.
291 TokenRequestURI string
292
293 // RenewCredentialRequestURI is the endpoint the client uses to
294 // request a new set of token credentials using the old set of credentials.
295 RenewCredentialRequestURI string
296
297 // TemporaryCredentialsMethod is the HTTP method used by the client to
298 // obtain a set of temporary credentials. If this field is the empty
299 // string, then POST is used.
300 TemporaryCredentialsMethod string
301
302 // TokenCredentailsMethod is the HTTP method used by the client to request
303 // a set of token credentials. If this field is the empty string, then POST
304 // is used.
305 TokenCredentailsMethod string
306
307 // Header specifies optional extra headers for requests.
308 Header http.Header
309
310 // SignatureMethod specifies the method for signing a request.
311 SignatureMethod SignatureMethod
312
313 // PrivateKey is the private key to use for RSA-SHA1 signatures. This field
314 // must be set for RSA-SHA1 signatures and ignored for other signature
315 // methods.
316 PrivateKey *rsa.PrivateKey
317 }
318
319 type request struct {
320 credentials *Credentials
321 method string
322 u *url.URL
323 form url.Values
324 verifier string
325 sessionHandle string
326 callbackURL string
327 }
328
329 var testHook = func(map[string]string) {}
330
331 // oauthParams returns the OAuth request parameters for the given credentials,
332 // method, URL and application params. See
333 // http://tools.ietf.org/html/rfc5849#section-3.4 for more information about
334 // signatures.
335 func (c *Client) oauthParams(r *request) (map[string]string, error) {
336 oauthParams := map[string]string{
337 "oauth_consumer_key": c.Credentials.Token,
338 "oauth_signature_method": c.SignatureMethod.String(),
339 "oauth_version": "1.0",
340 }
341
342 if c.SignatureMethod != PLAINTEXT {
343 oauthParams["oauth_timestamp"] = strconv.FormatInt(time.Now().Unix(), 10)
344 oauthParams["oauth_nonce"] = nonce()
345 }
346
347 if r.credentials != nil {
348 oauthParams["oauth_token"] = r.credentials.Token
349 }
350
351 if r.verifier != "" {
352 oauthParams["oauth_verifier"] = r.verifier
353 }
354
355 if r.sessionHandle != "" {
356 oauthParams["oauth_session_handle"] = r.sessionHandle
357 }
358
359 if r.callbackURL != "" {
360 oauthParams["oauth_callback"] = r.callbackURL
361 }
362
363 testHook(oauthParams)
364
365 var signature string
366
367 switch c.SignatureMethod {
368 case HMACSHA1:
369 key := encode(c.Credentials.Secret, false)
370 key = append(key, '&')
371 if r.credentials != nil {
372 key = append(key, encode(r.credentials.Secret, false)...)
373 }
374 h := hmac.New(sha1.New, key)
375 writeBaseString(h, r.method, r.u, r.form, oauthParams)
376 signature = base64.StdEncoding.EncodeToString(h.Sum(key[:0]))
377 case RSASHA1:
378 if c.PrivateKey == nil {
379 return nil, errors.New("oauth: private key not set")
380 }
381 h := sha1.New()
382 writeBaseString(h, r.method, r.u, r.form, oauthParams)
383 rawSignature, err := rsa.SignPKCS1v15(rand.Reader, c.PrivateKey, crypto.SHA1, h.Sum(nil))
384 if err != nil {
385 return nil, err
386 }
387 signature = base64.StdEncoding.EncodeToString(rawSignature)
388 case PLAINTEXT:
389 rawSignature := encode(c.Credentials.Secret, false)
390 rawSignature = append(rawSignature, '&')
391 if r.credentials != nil {
392 rawSignature = append(rawSignature, encode(r.credentials.Secret, false)...)
393 }
394 signature = string(rawSignature)
395 default:
396 return nil, errors.New("oauth: unknown signature method")
397 }
398
399 oauthParams["oauth_signature"] = signature
400 return oauthParams, nil
401 }
402
403 // SignForm adds an OAuth signature to form. The urlStr argument must not
404 // include a query string.
405 //
406 // See http://tools.ietf.org/html/rfc5849#section-3.5.2 for
407 // information about transmitting OAuth parameters in a request body and
408 // http://tools.ietf.org/html/rfc5849#section-3.5.2 for information about
409 // transmitting OAuth parameters in a query string.
410 func (c *Client) SignForm(credentials *Credentials, method, urlStr string, form url.Values) error {
411 u, err := url.Parse(urlStr)
412 switch {
413 case err != nil:
414 return err
415 case u.RawQuery != "":
416 return errors.New("oauth: urlStr argument to SignForm must not include a query string")
417 }
418 p, err := c.oauthParams(&request{credentials: credentials, method: method, u: u, form: form})
419 if err != nil {
420 return err
421 }
422 for k, v := range p {
423 form.Set(k, v)
424 }
425 return nil
426 }
427
428 // SignParam is deprecated. Use SignForm instead.
429 func (c *Client) SignParam(credentials *Credentials, method, urlStr string, params url.Values) {
430 u, _ := url.Parse(urlStr)
431 u.RawQuery = ""
432 p, _ := c.oauthParams(&request{credentials: credentials, method: method, u: u, form: params})
433 for k, v := range p {
434 params.Set(k, v)
435 }
436 }
437
438 var oauthKeys = []string{
439 "oauth_consumer_key",
440 "oauth_nonce",
441 "oauth_signature",
442 "oauth_signature_method",
443 "oauth_timestamp",
444 "oauth_token",
445 "oauth_version",
446 "oauth_callback",
447 "oauth_verifier",
448 "oauth_session_handle",
449 }
450
451 func (c *Client) authorizationHeader(r *request) (string, error) {
452 p, err := c.oauthParams(r)
453 if err != nil {
454 return "", err
455 }
456 var h []byte
457 // Append parameters in a fixed order to support testing.
458 for _, k := range oauthKeys {
459 if v, ok := p[k]; ok {
460 if h == nil {
461 h = []byte(`OAuth `)
462 } else {
463 h = append(h, ", "...)
464 }
465 h = append(h, k...)
466 h = append(h, `="`...)
467 h = append(h, encode(v, false)...)
468 h = append(h, '"')
469 }
470 }
471 return string(h), nil
472 }
473
474 // AuthorizationHeader returns the HTTP authorization header value for given
475 // method, URL and parameters.
476 //
477 // AuthorizationHeader is deprecated. Use SetAuthorizationHeader instead.
478 func (c *Client) AuthorizationHeader(credentials *Credentials, method string, u *url.URL, params url.Values) string {
479 // Signing a request can return an error. This method is deprecated because
480 // this method does not return an error.
481 v, _ := c.authorizationHeader(&request{credentials: credentials, method: method, u: u, form: params})
482 return v
483 }
484
485 // SetAuthorizationHeader adds an OAuth signature to a request header.
486 //
487 // See http://tools.ietf.org/html/rfc5849#section-3.5.1 for information about
488 // transmitting OAuth parameters in an HTTP request header.
489 func (c *Client) SetAuthorizationHeader(header http.Header, credentials *Credentials, method string, u *url.URL, form url.Values) error {
490 v, err := c.authorizationHeader(&request{credentials: credentials, method: method, u: u, form: form})
491 if err != nil {
492 return err
493 }
494 header.Set("Authorization", v)
495 return nil
496 }
497
498 func (c *Client) do(ctx context.Context, urlStr string, r *request) (*http.Response, error) {
499 var body io.Reader
500 if r.method != http.MethodGet {
501 body = strings.NewReader(r.form.Encode())
502 }
503 req, err := http.NewRequest(r.method, urlStr, body)
504 if err != nil {
505 return nil, err
506 }
507 if req.URL.RawQuery != "" {
508 return nil, errors.New("oauth: url must not contain a query string")
509 }
510 for k, v := range c.Header {
511 req.Header[k] = v
512 }
513 r.u = req.URL
514 auth, err := c.authorizationHeader(r)
515 if err != nil {
516 return nil, err
517 }
518 req.Header.Set("Authorization", auth)
519 if r.method == http.MethodGet {
520 req.URL.RawQuery = r.form.Encode()
521 } else {
522 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
523 }
524 req = req.WithContext(ctx)
525 client := contextClient(ctx)
526 return client.Do(req)
527 }
528
529 // Get issues a GET to the specified URL with form added as a query string.
530 func (c *Client) Get(client *http.Client, credentials *Credentials, urlStr string, form url.Values) (*http.Response, error) {
531 ctx := context.WithValue(context.Background(), HTTPClient, client)
532 return c.GetContext(ctx, credentials, urlStr, form)
533 }
534
535 // GetContext uses Context to perform Get.
536 func (c *Client) GetContext(ctx context.Context, credentials *Credentials, urlStr string, form url.Values) (*http.Response, error) {
537 return c.do(ctx, urlStr, &request{method: http.MethodGet, credentials: credentials, form: form})
538 }
539
540 // Post issues a POST with the specified form.
541 func (c *Client) Post(client *http.Client, credentials *Credentials, urlStr string, form url.Values) (*http.Response, error) {
542 ctx := context.WithValue(context.Background(), HTTPClient, client)
543 return c.PostContext(ctx, credentials, urlStr, form)
544 }
545
546 // PostContext uses Context to perform Post.
547 func (c *Client) PostContext(ctx context.Context, credentials *Credentials, urlStr string, form url.Values) (*http.Response, error) {
548 return c.do(ctx, urlStr, &request{method: http.MethodPost, credentials: credentials, form: form})
549 }
550
551 // Delete issues a DELETE with the specified form.
552 func (c *Client) Delete(client *http.Client, credentials *Credentials, urlStr string, form url.Values) (*http.Response, error) {
553 ctx := context.WithValue(context.Background(), HTTPClient, client)
554 return c.DeleteContext(ctx, credentials, urlStr, form)
555 }
556
557 // DeleteContext uses Context to perform Delete.
558 func (c *Client) DeleteContext(ctx context.Context, credentials *Credentials, urlStr string, form url.Values) (*http.Response, error) {
559 return c.do(ctx, urlStr, &request{method: http.MethodDelete, credentials: credentials, form: form})
560 }
561
562 // Put issues a PUT with the specified form.
563 func (c *Client) Put(client *http.Client, credentials *Credentials, urlStr string, form url.Values) (*http.Response, error) {
564 ctx := context.WithValue(context.Background(), HTTPClient, client)
565 return c.PutContext(ctx, credentials, urlStr, form)
566 }
567
568 // PutContext uses Context to perform Put.
569 func (c *Client) PutContext(ctx context.Context, credentials *Credentials, urlStr string, form url.Values) (*http.Response, error) {
570 return c.do(ctx, urlStr, &request{method: http.MethodPut, credentials: credentials, form: form})
571 }
572
573 func (c *Client) requestCredentials(ctx context.Context, u string, r *request) (*Credentials, url.Values, error) {
574 if r.method == "" {
575 r.method = http.MethodPost
576 }
577 resp, err := c.do(ctx, u, r)
578 if err != nil {
579 return nil, nil, err
580 }
581 p, err := ioutil.ReadAll(resp.Body)
582 resp.Body.Close()
583 if err != nil {
584 return nil, nil, RequestCredentialsError{StatusCode: resp.StatusCode, Header: resp.Header,
585 Body: p, msg: err.Error()}
586 }
587 if resp.StatusCode != 200 && resp.StatusCode != 201 {
588 return nil, nil, RequestCredentialsError{StatusCode: resp.StatusCode, Header: resp.Header,
589 Body: p, msg: fmt.Sprintf("OAuth server status %d, %s", resp.StatusCode, string(p))}
590 }
591 m, err := url.ParseQuery(string(p))
592 if err != nil {
593 return nil, nil, RequestCredentialsError{StatusCode: resp.StatusCode, Header: resp.Header,
594 Body: p, msg: err.Error()}
595 }
596 tokens := m["oauth_token"]
597 if len(tokens) == 0 || tokens[0] == "" {
598 return nil, nil, RequestCredentialsError{StatusCode: resp.StatusCode, Header: resp.Header,
599 Body: p, msg: "oauth: token missing from server result"}
600 }
601 secrets := m["oauth_token_secret"]
602 if len(secrets) == 0 { // allow "" as a valid secret.
603 return nil, nil, RequestCredentialsError{StatusCode: resp.StatusCode, Header: resp.Header,
604 Body: p, msg: "oauth: secret missing from server result"}
605 }
606 return &Credentials{Token: tokens[0], Secret: secrets[0]}, m, nil
607 }
608
609 // RequestTemporaryCredentials requests temporary credentials from the server.
610 // See http://tools.ietf.org/html/rfc5849#section-2.1 for information about
611 // temporary credentials.
612 func (c *Client) RequestTemporaryCredentials(client *http.Client, callbackURL string, additionalParams url.Values) (*Credentials, error) {
613 ctx := context.WithValue(context.Background(), HTTPClient, client)
614 return c.RequestTemporaryCredentialsContext(ctx, callbackURL, additionalParams)
615 }
616
617 // RequestTemporaryCredentialsContext uses Context to perform RequestTemporaryCredentials.
618 func (c *Client) RequestTemporaryCredentialsContext(ctx context.Context, callbackURL string, additionalParams url.Values) (*Credentials, error) {
619 credentials, _, err := c.requestCredentials(ctx, c.TemporaryCredentialRequestURI,
620 &request{method: c.TemporaryCredentialsMethod, form: additionalParams, callbackURL: callbackURL})
621 return credentials, err
622 }
623
624 // RequestToken requests token credentials from the server. See
625 // http://tools.ietf.org/html/rfc5849#section-2.3 for information about token
626 // credentials.
627 func (c *Client) RequestToken(client *http.Client, temporaryCredentials *Credentials, verifier string) (*Credentials, url.Values, error) {
628 ctx := context.WithValue(context.Background(), HTTPClient, client)
629 return c.RequestTokenContext(ctx, temporaryCredentials, verifier)
630 }
631
632 // RequestTokenContext uses Context to perform RequestToken.
633 func (c *Client) RequestTokenContext(ctx context.Context, temporaryCredentials *Credentials, verifier string) (*Credentials, url.Values, error) {
634 return c.requestCredentials(ctx, c.TokenRequestURI,
635 &request{credentials: temporaryCredentials, method: c.TokenCredentailsMethod, verifier: verifier})
636 }
637
638 // RenewRequestCredentials requests new token credentials from the server.
639 // See http://wiki.oauth.net/w/page/12238549/ScalableOAuth#AccessTokenRenewal
640 // for information about access token renewal.
641 func (c *Client) RenewRequestCredentials(client *http.Client, credentials *Credentials, sessionHandle string) (*Credentials, url.Values, error) {
642 ctx := context.WithValue(context.Background(), HTTPClient, client)
643 return c.RenewRequestCredentialsContext(ctx, credentials, sessionHandle)
644 }
645
646 // RenewRequestCredentialsContext uses Context to perform RenewRequestCredentials.
647 func (c *Client) RenewRequestCredentialsContext(ctx context.Context, credentials *Credentials, sessionHandle string) (*Credentials, url.Values, error) {
648 return c.requestCredentials(ctx, c.RenewCredentialRequestURI, &request{credentials: credentials, sessionHandle: sessionHandle})
649 }
650
651 // RequestTokenXAuth requests token credentials from the server using the xAuth protocol.
652 // See https://dev.twitter.com/oauth/xauth for information on xAuth.
653 func (c *Client) RequestTokenXAuth(client *http.Client, temporaryCredentials *Credentials, user, password string) (*Credentials, url.Values, error) {
654 ctx := context.WithValue(context.Background(), HTTPClient, client)
655 return c.RequestTokenXAuthContext(ctx, temporaryCredentials, user, password)
656 }
657
658 // RequestTokenXAuthContext uses Context to perform RequestTokenXAuth.
659 func (c *Client) RequestTokenXAuthContext(ctx context.Context, temporaryCredentials *Credentials, user, password string) (*Credentials, url.Values, error) {
660 form := make(url.Values)
661 form.Set("x_auth_mode", "client_auth")
662 form.Set("x_auth_username", user)
663 form.Set("x_auth_password", password)
664 return c.requestCredentials(ctx, c.TokenRequestURI,
665 &request{credentials: temporaryCredentials, method: c.TokenCredentailsMethod, form: form})
666 }
667
668 // AuthorizationURL returns the URL for resource owner authorization. See
669 // http://tools.ietf.org/html/rfc5849#section-2.2 for information about
670 // resource owner authorization.
671 func (c *Client) AuthorizationURL(temporaryCredentials *Credentials, additionalParams url.Values) string {
672 params := make(url.Values)
673 for k, vs := range additionalParams {
674 params[k] = vs
675 }
676 params.Set("oauth_token", temporaryCredentials.Token)
677 return c.ResourceOwnerAuthorizationURI + "?" + params.Encode()
678 }
679
680 // HTTPClient is the context key to use with context's
681 // WithValue function to associate an *http.Client value with a context.
682 var HTTPClient contextKey
683
684 type contextKey struct{}
685
686 func contextClient(ctx context.Context) *http.Client {
687 if ctx != nil {
688 if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok && hc != nil {
689 return hc
690 }
691 }
692 return http.DefaultClient
693 }
694
695 // RequestCredentialsError is an error containing
696 // response information when requesting credentials.
697 type RequestCredentialsError struct {
698 StatusCode int
699 Header http.Header
700 Body []byte
701 msg string
702 }
703
704 func (e RequestCredentialsError) Error() string {
705 return e.msg
706 }