-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOAuth.cs
1237 lines (1156 loc) · 52 KB
/
OAuth.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// http://cropperplugins.codeplex.com/SourceControl/latest#Cropper.Plugins/OAuth1.0/OAuth.cs
// OAuth/OAuth.cs
//
// Code to do OAuth stuff, in support of a cropper plugin that sends
// a screen snap to TwitPic.com or the other that sends to Twitter.
//
// There's one main class: OAuth.Manager. It handles interaction with the OAuth-
// enabled service, for requesting temporary tokens (aka request tokens), as well
// as access tokens. It also provides a convenient way to construct an oauth
// Authorization header for use in any Http transaction.
//
// The code has been tested with Twitter and TwitPic, from a desktop application.
//
// To build it standalone:
//
// csc.exe /target:library /D:STANDALONE /doc:OAuth.XML OAuth.cs
//
// -------------------------------------------------------
// Dino Chiesa
// Tue, 14 Dec 2010 12:31
//
// -------------------------------------------------------
// Last saved: <2012-May-18 15:36:17>
//
using System;
using System.Linq;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
#if STANDALONE
using System.Reflection;
// to allow fast ngen
[assembly: AssemblyTitle("OAuth.dll")]
[assembly: AssemblyDescription("A simple manager for the OAuth 1.0A authentication protocol.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dino Chiesa")]
[assembly: AssemblyProduct("Tools")]
[assembly: AssemblyCopyright("Copyright � Dino Chiesa 2011,2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.0")]
#endif
using CropperPlugins.Utils;
namespace OAuth
{
/// <summary>
/// A class to manage OAuth 1.0A interactions. This works with
/// Twitter; not sure about other OAuth-enabled services.
/// </summary>
/// <remarks>
/// <para>
/// This class holds the relevant oauth parameters, as well as
/// state for the oauth authentication dance. This class also
/// exposes methods that communicate with the OAuth provider, or
/// generate elaborated quantities (like Authorization header
/// strings) based on all the oauth properties.
/// </para>
/// <para>
/// OAuth 1.0A is ostensibly a standard, but as far as I am
/// aware, only Twitter implements the standard. Other services
/// implement *slightly* different oauth services. This class
/// has been tested to work only with Twitter.
/// </para>
/// <para>
/// See <see href="http://dev.twitpic.com/docs/2/upload/">
/// http://dev.twitpic.com/docs/2/upload/</see>
/// for an example of the oauth parameters. The parameters include token,
/// consumer_key, timestamp, version, and so on. In the actual HTTP
/// message, they all include the oauth_ prefix, so .. oauth_token,
/// oauth_timestamp, and so on. You set these via a string indexer.
/// If the instance of the class is called oauth, then to set the
/// oauth_token parameter, you use oath["token"] in C#.
/// </para>
/// <para>
/// This class automatically sets many of the required oauth parameters;
/// this includes the timestamp, nonce, callback, and version parameters.
/// (The callback param is initialized to 'oob'). You can reset any of
/// these parameters as you see fit. In many cases you won't have to.
/// </para>
/// <para>
/// The public methods on the class include:
/// AcquireRequestToken, AcquireAccessToken,
/// GenerateCredsHeader, and GenerateAuthzHeader. The
/// first two are used only on the first run of an applicaiton,
/// or after a user has explicitly de-authorized an application
/// for use with OAuth. Normally, the GenerateXxxHeader methods
/// can be used repeatedly, when sending HTTP messages that
/// require an OAuth Authorization header.
/// </para>
/// <para>
/// The AcquireRequestToken and AcquireAccessToken methods
/// actually send out HTTP messages.
/// </para>
/// <para>
/// The GenerateXxxxHeaders are used when constructing and
/// sending your own HTTP messages.
/// </para>
/// </remarks>
public class Manager
{
/// <summary>
/// The default public constructor.
/// </summary>
/// <remarks>
/// <para>
/// This constructor initializes the internal fields in the
/// Manager instance to default values.
/// </para>
/// </remarks>
public Manager()
{
_random = new Random();
_params = new Dictionary<String,String>();
_params["callback"] = "oob"; // presume "desktop" consumer
_params["consumer_key"] = "";
_params["consumer_secret"] = "";
_params["timestamp"] = GenerateTimeStamp();
_params["nonce"] = GenerateNonce();
_params["signature_method"] = "HMAC-SHA1";
_params["signature"] = "";
_params["token"] = "";
_params["token_secret"] = "";
_params["version"] = "1.0";
}
/// <summary>
/// The constructor to use when using OAuth when you already
/// have an OAuth access token.
/// </summary>
/// <remarks>
/// <para>
/// The parameters for this constructor all have the
/// meaning you would expect. The token and tokenSecret
/// are set in oauth_token, and oauth_token_secret.
/// These are *Access* tokens, obtained after a call
/// to AcquireAccessToken. The application can store
/// those tokens and re-use them on successive runs.
/// For twitter at least, the access tokens never expire.
/// </para>
/// </remarks>
///
/// <param name="consumerKey">The oauth_consumer_key parameter for
/// OAuth. Get this, along with the consumer secret value, by manually
/// registering your app with Twitter at
/// <see href="http://twitter.com/apps/new">http://twitter.com/apps/new</see>
/// </param>
///
/// <param name="consumerSecret">The oauth_consumer_secret
/// parameter for oauth.</param>
///
/// <param name="token">The oauth_token parameter for
/// oauth. This is sometimes called the Access Token.</param>
///
/// <param name="tokenSecret">The oauth_token_secret parameter for
/// oauth. This is sometimes called the Access Token Secret.</param>
public Manager(string consumerKey,
string consumerSecret,
string token,
string tokenSecret) : this()
{
_params["consumer_key"] = consumerKey;
_params["consumer_secret"] = consumerSecret;
_params["token"] = token;
_params["token_secret"] = tokenSecret;
}
/// <summary>
/// The constructor to use when using OAuth when you already
/// have an OAuth consumer key and sercret, but need to
/// acquire an oauth access token.
/// </summary>
/// <remarks>
/// <para>
/// The parameters for this constructor are the consumer_key
/// and consumer_secret that you get, manually, by
/// registering your application with Twitter.
/// </para>
/// <para>
/// What you need to do after instantiating the Manager
/// class with this constructor is set or obtain the access
/// key and token. See the examples provided elsewhere
/// for an illustration.
/// </para>
/// </remarks>
///
/// <param name="consumerKey">The oauth_consumer_key parameter for
/// oauth. Get this, along with the consumerSecret, by manually
/// registering your app with Twitter at
/// <see href="http://twitter.com/apps/new">http://twitter.com/apps/new</see>
/// </param>
///
/// <param name="consumerSecret">The oauth_consumer_secret
/// parameter for oauth.</param>
///
public Manager(string consumerKey, string consumerSecret) : this()
{
_params["consumer_key"] = consumerKey;
_params["consumer_secret"] = consumerSecret;
}
/// <summary>
/// The string indexer to get or set oauth parameter values.
/// </summary>
/// <remarks>
/// <para>
/// Use the parameter name *without* the oauth_ prefix. For
/// example, if you want to set the value for the
/// oauth_token parameter field in an HTTP message, then use
/// oauth["token"].
/// </para>
/// <para>
/// The set of oauth param names known by this indexer includes:
/// callback, consumer_key, consumer_secret, timestamp, nonce,
/// signature_method, signature, token, token_secret, and version.
/// </para>
/// <para>
/// If you try setting a parameter with a name that is not known,
/// the setter will throw. You cannot "add" new oauth parameters
/// using the setter on this indexer.
/// </para>
/// </remarks>
///
/// <example>
/// This shows how to set the oauth_consumer_key and
/// oauth_consumer_secret using the indexer. Notice that the string
/// values lack the oauth_ prefix.
/// <code>
/// var oauth = new OAuth.Manager();
/// oauth["consumer_key"] = "~~~CONSUMER_KEY~~~~";
/// oauth["consumer_secret"] = "~~~CONSUMER_SECRET~~~";
/// oauth.AcquireRequestToken();
/// </code>
/// </example>
public string this[string ix]
{
get
{
if (_params.ContainsKey(ix))
return _params[ix];
throw new ArgumentException(ix);
}
set
{
if (!_params.ContainsKey(ix))
throw new ArgumentException(ix);
_params[ix] = value;
}
}
/// <summary>
/// Generate the timestamp for the signature.
/// </summary>
///
/// <returns>The timestamp, in string form.</returns>
private string GenerateTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - _epoch;
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
/// <summary>
/// Renews the nonce and timestamp on the oauth parameters.
/// </summary>
/// <remarks>
/// <para>
/// Each new request should get a new, current timestamp, and a
/// nonce. This helper method does both of those things. This gets
/// called before generating an authorization header, as for example
/// when the user of this class calls <see cref='AcquireRequestToken()'/>.
/// </para>
/// </remarks>
private void NewRequest()
{
_params["nonce"] = GenerateNonce();
_params["timestamp"] = GenerateTimeStamp();
}
/// <summary>
/// Generate an oauth nonce.
/// </summary>
/// <remarks>
/// <para>
/// According to <see
/// href="http://tools.ietf.org/html/rfc5849">RFC 5849</see>, A
/// nonce is a random string, uniquely generated by the client to
/// allow the server to verify that a request has never been made
/// before and helps prevent replay attacks when requests are made
/// over a non-secure channel. The nonce value MUST be unique
/// across all requests with the same timestamp, client
/// credentials, and token combinations.
/// </para>
/// <para>
/// One way to implement the nonce is just to use a
/// monotonically-increasing integer value. It starts at zero and
/// increases by 1 for each new request or signature generated.
/// Keep in mind the nonce needs to be unique only for a given
/// timestamp! So if your app makes less than one request per
/// second, then using a static nonce of "0" will work.
/// </para>
/// <para>
/// Most oauth nonce generation routines are waaaaay over-engineered,
/// and this one is no exception.
/// </para>
/// </remarks>
/// <returns>the nonce</returns>
private string GenerateNonce()
{
var sb = new System.Text.StringBuilder();
for (int i=0; i < 8; i++)
{
int g = _random.Next(3);
switch(g)
{
case 0:
// lowercase alpha
sb.Append( (char)(_random.Next(26)+97), 1);
break;
default:
// numeric digits
sb.Append( (char)(_random.Next(10)+48), 1);
break;
}
}
return sb.ToString();
}
/// <summary>
/// Internal function to extract from a URL all query string
/// parameters that are not related to oauth - in other words all
/// parameters not begining with "oauth_".
/// </summary>
///
/// <remarks>
/// <para>
/// For example, given a url like http://foo?a=7&guff, the
/// returned value will be a Dictionary of string-to-string
/// relations. There will be 2 entries in the Dictionary: "a"=>7,
/// and "guff"=>"".
/// </para>
/// </remarks>
///
/// <param name="queryString">The query string part of the Url</param>
///
/// <returns>A Dictionary containing the set of
/// parameter names and associated values</returns>
private List<KeyValuePair<String,String>> ExtractQueryParameters(string queryString)
{
if (queryString.StartsWith("?"))
queryString = queryString.Remove(0, 1);
var result = new List<KeyValuePair<String, String>>();
if (string.IsNullOrEmpty(queryString))
return result;
foreach (string s in queryString.Split('&'))
{
if (!string.IsNullOrEmpty(s) && !s.StartsWith("oauth_"))
{
if (s.IndexOf('=') > -1)
{
string[] temp = s.Split('=');
result.Add(new KeyValuePair<string, string>(temp[0], temp[1]));
}
else
result.Add(new KeyValuePair<string, string>(s, string.Empty));
}
}
return result;
}
/// <summary>
/// This method performs oauth-compliant Url Encoding.
/// </summary>
/// <remarks>
/// <para>
/// This class provides an OAuth-friendly URL encoder. .NET includes
/// a Url encoder in the base class library; see <see
/// href='http://msdn.microsoft.com/en-us/library/zttxte6w(v=VS.90).aspx'>
/// HttpServerUtility.UrlEncode</see>. But that encoder is not
/// sufficient for use with OAuth.
/// </para>
/// <para>
/// The builtin encoder emits the percent encoding in lower case,
/// which works for HTTP purposes, as described in the latest HTTP
/// specification (see <see
/// href="http://tools.ietf.org/html/rfc3986">RFC 3986</see>). But the
/// Oauth specification, provided in <see
/// href="http://tools.ietf.org/html/rfc5849">RFC 5849</see>, requires
/// that the encoding characters be upper case throughout OAuth.
/// </para>
/// <para>
/// For example, if you try to post a tweet message that includes a
/// forward slash, the slash needs to be encoded as %2F, and the
/// second hex digit needs to be uppercase.
/// </para>
/// <para>
/// It's not enough to simply convert the entire message to uppercase,
/// because that would of course convert un-encoded characters to
/// uppercase as well, which is undesirable. This class provides an
/// OAuth-friendly encoder to do the right thing.
/// </para>
/// </remarks>
///
/// <param name="value">The value to encode</param>
///
/// <example>
/// <code>
/// var twitterUpdateUrlBase = "http://api.twitter.com/1/statuses/update.xml?status=";
/// var url = twitterUpdateUrlBase + OAuth.Manager.UrlEncode(message);
/// var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
/// var request = (HttpWebRequest)WebRequest.Create(url);
/// request.Method = "POST";
/// request.PreAuthenticate = true;
/// request.AllowWriteStreamBuffering = true;
/// request.Headers.Add("Authorization", authzHeader);
/// using (var response = (HttpWebResponse)request.GetResponse())
/// {
/// ...
/// }
/// </code>
/// </example>
/// <returns>the Url-encoded version of that string</returns>
public static string UrlEncode(string value)
{
var result = new StringBuilder();
foreach (char symbol in value)
{
if (unreservedChars.IndexOf(symbol) != -1)
result.Append(symbol);
else
{
foreach (byte b in Encoding.UTF8.GetBytes(symbol.ToString()))
{
result.Append('%' + String.Format("{0:X2}", b));
}
}
}
return result.ToString();
}
private static string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
/// <summary>
/// Formats the list of request parameters into string a according
/// to the requirements of oauth. The resulting string could be used
/// in the Authorization header of the request.
/// </summary>
///
/// <remarks>
/// <para>
/// See <see
/// href="http://dev.twitter.com/pages/auth#intro">Twitter's OAUth
/// documentation page</see> for some background. The output of
/// this call is not suitable for signing.
/// </para>
/// <para>
/// There are 2 formats for specifying the list of oauth
/// parameters in the oauth spec: one suitable for signing, and
/// the other suitable for use within Authorization HTTP Headers.
/// This method emits a string suitable for the latter.
/// </para>
/// </remarks>
///
/// <param name="p">The Dictionary of parameters. It need not be
/// sorted. Actually, strictly speaking, it need not be a
/// dictionary, either. Just a collection of KeyValuePair.</param>
///
/// <returns>a string representing the parameters</returns>
private static string EncodeRequestParameters(ICollection<KeyValuePair<String,String>> p)
{
var sb = new System.Text.StringBuilder();
foreach (KeyValuePair<String,String> item in p.OrderBy(x => x.Key))
{
if (!String.IsNullOrEmpty(item.Value) &&
!item.Key.EndsWith("secret"))
sb.AppendFormat("oauth_{0}=\"{1}\", ",
item.Key,
UrlEncode(item.Value));
}
return sb.ToString().TrimEnd(' ').TrimEnd(',');
}
/// <summary>
/// Acquire a request token from the given URI using the given
/// HTTP method.
/// </summary>
///
/// <remarks>
/// <para>
/// To use this method, first instantiate a new Oauth.Manager
/// object, then, optionally, set the callback param
/// (oauth["callback"]='oob'). Consult the Twitter documentation
/// for the meaning and usage of the callback parameter. After the
/// call returns, you should direct the user to open a browser
/// window to the authorization page for the OAuth-enabled
/// service. Or, you can automatically open that page yourself. Do
/// this with System.Diagnostics.Process.Start(), passing the URL
/// of the page. If you're using Twitter, there should be one
/// query param: oauth_token with the value obtained from
/// oauth["token"]. See the example
/// </para>
/// <para>
/// According to the OAuth spec, you need to do this only ONCE per
/// application, the first time the application is run. The
/// normal oauth workflow is: (1) get a request token, (2) use
/// that to acquire an access token (which requires explicit user
/// approval), then (3) using that access token, invoke protected
/// services. The first two steps need to be done only once, ever,
/// for each registered application. The third step can be
/// performed many times, over many invocations of the
/// application.
/// </para>
/// <para>
/// For Twitter, at least, you can cache the access tokens
/// indefinitely; Twitter says they never expire. However, other
/// oauth services may not do the same. Also: the user may at any
/// time revoke his authorization for your app, in which case you
/// need to perform the first 2 steps again.
/// </para>
/// </remarks>
///
/// <seealso cref='AcquireAccessToken(string,string,string)'/>
/// <seealso cref='AcquireAccessToken(string)'/>
///
/// <example>
/// <para>
/// This example shows how to request an access token and key
/// from Twitter. It presumes you've already obtained a
/// consumer key and secret via app registration. Requesting
/// an access token is necessary only the first time you
/// contact the service. You can cache the access key and
/// token for subsequent runs, later.
/// </para>
/// <code>
/// // the URL to obtain a temporary "request token"
/// var rtUrl = "https://api.twitter.com/oauth/request_token";
/// var oauth = new OAuth.Manager();
/// // The consumer_{key,secret} are obtained via registration
/// oauth["consumer_key"] = "~~~CONSUMER_KEY~~~~";
/// oauth["consumer_secret"] = "~~~CONSUMER_SECRET~~~";
/// oauth.AcquireRequestToken(rtUrl, "POST");
/// // The request token is now available in oauth["token"]
/// // The next step is to pop the authorization approval dialog.
/// var authzUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth["token"];
/// System.Diagnostics.Process.Start(authzUrl);
/// </code>
/// </example>
///
/// <param name="uri">The uri to the "request token" endpoint of
/// the service that implements oauth. For Twitter, this is
/// "https://api.twitter.com/oauth/request_token".
/// </param>
///
/// <param name="method">The method you will use to send the
/// message asking for a request token. For Twitter, this
/// should be "POST".
/// </param>
///
/// <returns>
/// a response object that contains the entire text of the response,
/// as well as extracted parameters. This method presumes the
/// response is query-param encoded. In other words,
/// poauth_token=foo&something_else=bar.
/// </returns>
public OAuthResponse AcquireRequestToken(string uri, string method)
{
NewRequest();
var authzHeader = GetAuthorizationHeader(uri, method);
// prepare the token request
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
request.Headers.Add("Authorization", authzHeader);
request.Method = method;
using (var response = (System.Net.HttpWebResponse)request.GetResponse())
{
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
{
var r = new OAuthResponse(reader.ReadToEnd());
this["token"] = r["oauth_token"];
// Sometimes the request_token URL gives us an access token,
// with no user interaction required. Eg, when prior approval
// has already been granted.
try
{
if (r["oauth_token_secret"] != null)
this["token_secret"] = r["oauth_token_secret"];
}
catch { }
return r;
}
}
}
/// <summary>
/// Acquire a request token for Twitter using the default endpoint
/// and HTTP method (POST).
/// </summary>
///
/// <remarks>
/// <para>
/// To use this method, first instantiate a new Oauth.Manager object,
/// then set the callback param (oauth["callback"]='oob'). After the
/// call returns, you should direct the user to open a browser window
/// to the authorization page for the OAuth-enabled service. Or,
/// you can automatically open that page yourself. Do this with
/// System.Diagnostics.Process.Start(), passing the URL of the page.
/// There should be one query param: oauth_token with the value
/// obtained from oauth["token"].
/// </para>
/// <para>
/// According to the OAuth spec, you need to do this only ONCE per
/// application. In other words, the first time the application
/// is run. The normal oauth workflow is: (1) get a request token,
/// (2) use that to acquire an access token (which requires explicit
/// user approval), then (3) using that access token, invoke
/// protected services. The first two steps need to be done only
/// once per application.
/// </para>
/// <para>
/// For Twitter, at least, you can cache the access tokens
/// indefinitely; Twitter says they never expire. However, other
/// oauth services may not do the same. Also: the user may at any
/// time revoke his authorization for your app, in which case you
/// need to perform the first 2 steps again.
/// </para>
/// </remarks>
///
/// <seealso cref='AcquireAccessToken(string,string,string)'/>
/// <seealso cref='AcquireAccessToken(string)'/>
/// <seealso cref='AcquireRequestToken(string,string)'/>
///
/// <example>
/// <para>
/// This example shows how to request an access token and key
/// from Twitter. It presumes you've already obtained a
/// consumer key and secret via app registration. Requesting
/// an access token is necessary only the first time you
/// contact the service. You can cache the access key and
/// token for subsequent runs, later.
/// </para>
/// <code>
/// var oauth = new OAuth.Manager();
/// // The consumer_{key,secret} are obtained via registration
/// oauth["consumer_key"] = "~~~CONSUMER_KEY~~~~";
/// oauth["consumer_secret"] = "~~~CONSUMER_SECRET~~~";
/// oauth.AcquireRequestToken();
/// // The request token is now available in oauth["token"]
/// // The next step is to pop the authorization approval dialog.
/// var authzUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth["token"];
/// System.Diagnostics.Process.Start(authzUrl);
/// </code>
/// </example>
///
/// <returns>
/// a response object that contains the entire text of the response,
/// as well as extracted parameters. This method presumes the
/// response is query-param encoded. In other words,
/// poauth_token=foo&something_else=bar.
/// </returns>
public OAuthResponse AcquireRequestToken()
{
return AcquireRequestToken("https://api.twitter.com/oauth/request_token",
"POST");
}
/// <summary>
/// Acquire an access token, from the given URI, using the given
/// HTTP method.
/// </summary>
///
/// <remarks>
/// <para>
/// To use this method, you must first set the oauth_token to the value
/// of the request token. Eg, oauth["token"] = "whatever".
/// </para>
/// <para>
/// According to the OAuth spec, you need to do this only ONCE per
/// application. In other words, the first time the application
/// is run. The normal oauth workflow is: (1) get a request token,
/// (2) use that to acquire an access token (which requires explicit
/// user approval), then (3) using that access token, invoke
/// protected services. The first two steps need to be done only
/// once per application.
/// </para>
/// <para>
/// For Twitter, at least, you can cache the access tokens
/// indefinitely; Twitter says they never expire. However, other
/// oauth services may not do the same. Also: the user may at any
/// time revoke his authorization for your app, in which case you
/// need to perform the first 2 steps again.
/// </para>
/// </remarks>
///
/// <seealso cref='AcquireRequestToken()'/>
///
/// <example>
/// <para>
/// This example shows how to request an access token and key
/// from Twitter. It presumes you've already obtained a
/// consumer key and secret via app registration. Requesting
/// an access token is necessary only the first time you
/// contact the service. You can cache the access key and
/// token for subsequent runs, later.
/// </para>
/// <code>
/// // the URL to obtain a temporary "request token"
/// var rtUrl = "https://api.twitter.com/oauth/request_token";
/// var oauth = new OAuth.Manager();
/// // The consumer_{key,secret} are obtained via registration
/// oauth["consumer_key"] = "~~~CONSUMER_KEY~~~~";
/// oauth["consumer_secret"] = "~~~CONSUMER_SECRET~~~";
/// oauth.AcquireRequestToken(rtUrl, "POST");
/// var authzUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth["token"];
/// // Normally you'd want to pop this in a WebBrowser control.
/// // For the example only, we'll pop the URL in a separate browser.
/// System.Diagnostics.Process.Start(authzUrl);
/// // instruct the user to type in the PIN from that browser window
/// var pin = "...";
/// var atUrl = "https://api.twitter.com/oauth/access_token";
/// oauth.AcquireAccessToken(atUrl, "POST", pin);
///
/// // now, update twitter status using that access token
/// var appUrl = "http://api.twitter.com/1/statuses/update.xml?status=Hello";
/// var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
/// var request = (HttpWebRequest)WebRequest.Create(appUrl);
/// request.Method = "POST";
/// request.PreAuthenticate = true;
/// request.AllowWriteStreamBuffering = true;
/// request.Headers.Add("Authorization", authzHeader);
///
/// using (var response = (HttpWebResponse)request.GetResponse())
/// {
/// if (response.StatusCode != HttpStatusCode.OK)
/// MessageBox.Show("There's been a problem trying to tweet:" +
/// Environment.NewLine +
/// response.StatusDescription);
/// }
/// </code>
/// </example>
///
/// <param name="uri">The uri to the "access token" endpoint of
/// the service that implements oauth. For Twitter, this is
/// "https://api.twitter.com/oauth/access_token".
/// </param>
///
/// <param name="method">The method you will use to send the
/// message asking for an access token. For Twitter, this
/// should be "POST".
/// </param>
///
/// <param name="pin">The PIN returned by the "Application approval" page
/// shown by Twitter. It's a string of numeric digits, 7 or so digits in
/// length.
/// </param>
///
/// <returns>
/// a response object that contains the entire text of the response,
/// as well as extracted parameters. This method presumes the
/// response is query-param encoded. In other words,
/// oauth_token=foo&something_else=bar.
/// </returns>
public OAuthResponse AcquireAccessToken(string uri, string method, string pin)
{
Tracing.Trace("AcquireAccessToken.");
NewRequest();
_params.Remove("callback"); // no longer needed
_params["verifier"] = pin;
var authzHeader = GetAuthorizationHeader(uri, method);
try
{
// prepare the token request
var request = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(uri);
request.Headers.Add("Authorization", authzHeader);
request.Method = method;
using (var response = (System.Net.HttpWebResponse)request.GetResponse())
{
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
{
var s = reader.ReadToEnd();
Tracing.Trace("resp: {0}", s);
var r = new OAuthResponse(s);
this["token"] = r["oauth_token"];
this["token_secret"] = r["oauth_token_secret"];
_params.Remove("verifier"); // not needed any longer
return r;
}
}
}
catch (Exception ex1)
{
Tracing.Trace("Exception: {0}", ex1.ToString());
_params.Remove("verifier"); // not needed any longer
return null;
}
}
/// <summary>
/// Acquire an access token for Twitter, using the default endpoint and
/// HTTP method.
/// </summary>
/// <remarks>
/// <para>
/// To use this method, you must first set the oauth_token to the value
/// of the request token. Eg, oauth["token"] = "whatever".
/// </para>
/// <para>
/// According to the OAuth spec, you need to do this only ONCE per
/// application, the first time the application is run. The
/// normal oauth workflow is: (1) get a request token, (2) use
/// that to acquire an access token (which requires explicit user
/// approval), then (3) using that access token, invoke protected
/// services. The first two steps need to be done only once per
/// application.
/// </para>
/// <para>
/// For Twitter, at least, you can cache the access tokens
/// indefinitely; Twitter says they never expire. However,
/// other oauth services may not do the same. Also: the user
/// may at any time revoke his authorization for your app,
/// in which case you will get 403 errors. In that case you
/// need to perform the first 2 steps again.
/// </para>
/// </remarks>
///
/// <seealso cref='AcquireRequestToken()'/>
///
/// <example>
/// <para>
/// This example shows how to request an access token and key
/// from Twitter. It presumes you've already obtained a
/// consumer key and secret via app registration. Requesting
/// an access token is necessary only the first time you
/// contact the service. You can cache the access key and
/// token for subsequent runs, later.
/// </para>
/// <code>
/// var oauth = new OAuth.Manager();
/// // The consumer_{key,secret} are obtained via registration
/// oauth["consumer_key"] = "~~~CONSUMER_KEY~~~~";
/// oauth["consumer_secret"] = "~~~CONSUMER_SECRET~~~";
/// oauth.AcquireRequestToken();
/// var authzUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth["token"];
/// System.Diagnostics.Process.Start(authzUrl);
/// // instruct the user to type in the PIN from that browser window
/// var pin = "...";
/// oauth.AcquireAccessToken(pin);
///
/// // now, update twitter status using that access token
/// var appUrl = "http://api.twitter.com/1/statuses/update.xml?status=Hello";
/// var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
/// var request = (HttpWebRequest)WebRequest.Create(appUrl);
/// request.Method = "POST";
/// request.PreAuthenticate = true;
/// request.AllowWriteStreamBuffering = true;
/// request.Headers.Add("Authorization", authzHeader);
///
/// using (var response = (HttpWebResponse)request.GetResponse())
/// {
/// if (response.StatusCode != HttpStatusCode.OK)
/// MessageBox.Show("There's been a problem trying to tweet:" +
/// Environment.NewLine +
/// response.StatusDescription);
/// }
/// </code>
/// </example>
///
/// <param name="pin">The PIN returned by the "Application approval" page
/// shown by Twitter. It's a string of numeric digits, 7 or so digits in
/// length.
/// </param>
///
/// <returns>
/// a response object that contains the entire text of the response,
/// as well as extracted parameters. This method presumes the
/// response is query-param encoded. In other words,
/// oauth_token=foo&something_else=bar.
/// </returns>
public OAuthResponse AcquireAccessToken(string pin)
{
return AcquireAccessToken("https://api.twitter.com/oauth/access_token",
"POST",
pin);
}
/// <summary>
/// Generate a string to be used in an Authorization header in
/// an HTTP request.
/// </summary>
/// <remarks>
/// <para>
/// This method assembles the available oauth_ parameters that
/// have been set in the Dictionary in this instance, produces
/// the signature base (As described by the OAuth spec, RFC 5849),
/// signs it, then re-formats the oauth_ parameters into the
/// appropriate form, including the oauth_signature value, and
/// returns the result.
/// </para>
/// <para>
/// If you pass in a non-null, non-empty realm, this method will
/// include the realm='foo' clause in the generated Authorization header.
/// </para>
/// </remarks>
///
/// <seealso cref='GenerateAuthzHeader'/>
///
/// <param name="uri">The "verify credentials" endpoint for the
/// service to communicate with, via an OAuth-authenticated
/// message. For Twitpic (authenticated through Twitter), this is
/// "https://api.twitter.com/1/account/verify_credentials.json".
/// </param>
///
/// <param name="method">The HTTP method to use to request the
/// credentials verification. For Twitpic (authenticated
/// through Twitter), this is "GET".</param>
///
/// <param name="realm">The "Realm" to use to verify
/// credentials. For Twitpic (authenticated through Twitter),
/// this is "http://api.twitter.com/".</param>
///
/// <returns>The OAuth authorization header parameter that has been
/// generated given all the oauth input parameters.</returns>
public string GenerateCredsHeader(string uri, string method, string realm)
{
NewRequest();
var authzHeader = GetAuthorizationHeader(uri, method, realm);
return authzHeader;
}
/// <summary>
/// Generate a string to be used in an Authorization header in
/// an HTTP request.
/// </summary>
/// <remarks>
/// <para>
/// This method assembles the available oauth_ parameters that
/// have been set in the Dictionary in this instance, produces
/// the signature base (As described by the OAuth spec, RFC 5849),
/// signs it, then re-formats the oauth_ parameters into the
/// appropriate form, including the oauth_signature value, and
/// returns the result.
/// </para>
/// </remarks>
///
/// <example>
/// <para>
/// This example shows how to update the Twitter status
/// using the stored consumer key and secret, and a previously
/// obtained access token and secret.
/// </para>
/// <code>
/// var oauth = new OAuth.Manager();
/// oauth["consumer_key"] = "~~ your stored consumer key ~~";
/// oauth["consumer_secret"] = "~~ your stored consumer secret ~~";
/// oauth["token"] = "~~ your stored access token ~~";
/// oauth["token_secret"] = "~~ your stored access secret ~~";
/// var appUrl = "http://api.twitter.com/1/statuses/update.xml?status=Hello";
/// var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
/// var request = (HttpWebRequest)WebRequest.Create(appUrl);
/// request.Method = "POST";
/// request.PreAuthenticate = true;
/// request.AllowWriteStreamBuffering = true;
/// request.Headers.Add("Authorization", authzHeader);
///
/// using (var response = (HttpWebResponse)request.GetResponse())
/// {
/// if (response.StatusCode != HttpStatusCode.OK)
/// MessageBox.Show("There's been a problem trying to tweet:" +
/// Environment.NewLine +
/// response.StatusDescription);
/// }
/// </code>
/// </example>
///
/// <seealso cref='GenerateCredsHeader'/>