Skip to content

Instantly share code, notes, and snippets.

@tsupo
Created March 15, 2010 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsupo/333447 to your computer and use it in GitHub Desktop.
Save tsupo/333447 to your computer and use it in GitHub Desktop.
OAuth library for Twitter and Jaiku (Twitter's xAuth ready)
/* forked http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs */
using System;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace OAuth
{
public class OAuthBase
{
/// <summary>
/// Provides a predefined set of algorithms that are supported officially by the protocol
/// </summary>
public enum SignatureTypes
{
HMACSHA1,
PLAINTEXT,
RSASHA1
}
/// <summary>
/// Provides an internal structure to sort the query parameter
/// </summary>
protected class QueryParameter
{
private string name = null;
private string value = null;
public QueryParameter(string name, string value)
{
this.name = name;
this.value = value;
}
public string Name
{
get { return name; }
}
public string Value
{
get { return value; }
}
}
/// <summary>
/// Comparer class used to perform the sorting of the query parameters
/// </summary>
protected class QueryParameterComparer : IComparer<QueryParameter>
{
#region IComparer<QueryParameter> Members
public int Compare(QueryParameter x, QueryParameter y)
{
if (x.Name == y.Name)
{
return string.Compare(x.Value, y.Value);
}
else
{
return string.Compare(x.Name, y.Name);
}
}
#endregion
}
protected const string OAuthVersion = "1.0";
protected const string OAuthParameterPrefix = "oauth_";
//
// List of know and used oauth parameters' names
//
protected const string OAuthConsumerKeyKey = "oauth_consumer_key";
protected const string OAuthCallbackKey = "oauth_callback";
protected const string OAuthVersionKey = "oauth_version";
protected const string OAuthSignatureMethodKey = "oauth_signature_method";
protected const string OAuthSignatureKey = "oauth_signature";
protected const string OAuthTimestampKey = "oauth_timestamp";
protected const string OAuthNonceKey = "oauth_nonce";
protected const string OAuthTokenKey = "oauth_token";
protected const string OAuthTokenSecretKey = "oauth_token_secret";
protected const string OAuthVerifier = "oauth_verifier"; // OAuth 1.0a
protected const string HMACSHA1SignatureType = "HMAC-SHA1";
protected const string PlainTextSignatureType = "PLAINTEXT";
protected const string RSASHA1SignatureType = "RSA-SHA1";
protected Random random = new Random();
protected string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
/// <summary>
/// Helper function to compute a hash value
/// </summary>
/// <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm needs some initialization, like HMAC and its derivatives, they should be initialized prior to passing it to this function</param>
/// <param name="data">The data to hash</param>
/// <returns>a Base64 string of the hash value</returns>
private string ComputeHash(HashAlgorithm hashAlgorithm, string data)
{
if (hashAlgorithm == null)
{
throw new ArgumentNullException("hashAlgorithm");
}
if (string.IsNullOrEmpty(data))
{
throw new ArgumentNullException("data");
}
byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(data);
byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
/// <summary>
/// Internal function to cut out all non oauth query string parameters (all parameters not begining with "oauth_")
/// </summary>
/// <param name="parameters">The query string part of the Url</param>
/// <returns>A list of QueryParameter each containing the parameter name and value</returns>
private List<QueryParameter> GetQueryParameters(string parameters)
{
if (parameters.StartsWith("?"))
{
parameters = parameters.Remove(0, 1);
}
List<QueryParameter> result = new List<QueryParameter>();
if (!string.IsNullOrEmpty(parameters))
{
string[] p = parameters.Split('&');
foreach (string s in p)
{
if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix))
{
if (s.IndexOf('=') > -1)
{
string[] temp = s.Split('=');
result.Add(new QueryParameter(temp[0], temp[1]));
}
else
{
result.Add(new QueryParameter(s, string.Empty));
}
}
}
}
return result;
}
/// <summary>
/// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case.
/// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth
/// </summary>
/// <param name="value">The value to Url encode</param>
/// <returns>Returns a Url encoded string</returns>
protected string UrlEncode(string value)
{
StringBuilder result = new StringBuilder();
foreach (char symbol in value)
{
if (unreservedChars.IndexOf(symbol) != -1)
{
result.Append(symbol);
}
else
{
result.Append('%' + String.Format("{0:X2}", (int)symbol));
}
}
return result.ToString();
}
// added by H.Tsujimura 20090406 (for multibyte characters; cf. Japanese, Chinese, ......)
protected string UrlEncode(string value, Encoding encode)
{
StringBuilder result = new StringBuilder();
byte[] data = encode.GetBytes(value);
int len = data.Length;
for (int i = 0; i < len; i++)
{
int c = data[i];
if (c < 0x80 && unreservedChars.IndexOf((char)c) != -1)
{
result.Append((char)c);
}
else
{
result.Append('%' + String.Format("{0:X2}", (int)data[i]));
}
}
return result.ToString();
}
/// <summary>
/// Normalizes the request parameters according to the spec
/// </summary>
/// <param name="parameters">The list of parameters already sorted</param>
/// <returns>a string representing the normalized parameters</returns>
protected string NormalizeRequestParameters(IList<QueryParameter> parameters)
{
StringBuilder sb = new StringBuilder();
QueryParameter p = null;
for (int i = 0; i < parameters.Count; i++)
{
p = parameters[i];
sb.AppendFormat("{0}={1}", p.Name, p.Value);
if (i < parameters.Count - 1)
{
sb.Append("&");
}
}
return sb.ToString();
}
/// <summary>
/// Generate the signature base that is used to produce the signature
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <param name="signatureType">The signature type. To use the default values use <see cref="OAuthBase.SignatureTypes">OAuthBase.SignatureTypes</see>.</param>
/// <returns>The signature base</returns>
public string GenerateSignatureBase(
Uri url, string consumerKey, string token, string tokenSecret,
string httpMethod, string timeStamp, string nonce, string signatureType,
string verifier,
out string normalizedUrl, out string normalizedRequestParameters)
{
if (token == null)
{
token = string.Empty;
}
if (tokenSecret == null)
{
tokenSecret = string.Empty;
}
if (string.IsNullOrEmpty(consumerKey))
{
throw new ArgumentNullException("consumerKey");
}
if (string.IsNullOrEmpty(httpMethod))
{
throw new ArgumentNullException("httpMethod");
}
if (string.IsNullOrEmpty(signatureType))
{
throw new ArgumentNullException("signatureType");
}
normalizedUrl = null;
normalizedRequestParameters = null;
List<QueryParameter> parameters = GetQueryParameters(url.Query);
parameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion));
parameters.Add(new QueryParameter(OAuthNonceKey, nonce));
parameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp));
parameters.Add(new QueryParameter(OAuthSignatureMethodKey, signatureType));
parameters.Add(new QueryParameter(OAuthConsumerKeyKey, consumerKey));
if (verifier != null && verifier != "")
parameters.Add(new QueryParameter(OAuthVerifier, verifier));
if (!string.IsNullOrEmpty(token))
{
parameters.Add(new QueryParameter(OAuthTokenKey, token));
}
parameters.Sort(new QueryParameterComparer());
normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host);
if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
{
normalizedUrl += ":" + url.Port;
}
normalizedUrl += url.AbsolutePath;
normalizedRequestParameters = NormalizeRequestParameters(parameters);
StringBuilder signatureBase = new StringBuilder();
signatureBase.AppendFormat("{0}&", httpMethod.ToUpper());
signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));
return signatureBase.ToString();
}
/// <summary>
/// Generate the signature value based on the given signature base and hash algorithm
/// </summary>
/// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param>
/// <param name="hash">The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash)
{
return ComputeHash(hash, signatureBase);
}
/// <summary>
/// Generates a signature using the HMAC-SHA1 algorithm
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="consumerSecret">The consumer seceret</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignature(
Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret,
string httpMethod, string timeStamp, string nonce,
out string normalizedUrl, out string normalizedRequestParameters)
{
return GenerateSignature(
url, consumerKey, consumerSecret, token, tokenSecret,
httpMethod, timeStamp, nonce, SignatureTypes.HMACSHA1, null,
out normalizedUrl, out normalizedRequestParameters);
}
public string GenerateSignature(
Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret,
string httpMethod, string timeStamp, string nonce,
string verifier,
out string normalizedUrl, out string normalizedRequestParameters)
{
return GenerateSignature(
url, consumerKey, consumerSecret, token, tokenSecret,
httpMethod, timeStamp, nonce, SignatureTypes.HMACSHA1, verifier,
out normalizedUrl, out normalizedRequestParameters);
}
/// <summary>
/// Generates a signature using the specified signatureType
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="consumerSecret">The consumer seceret</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <param name="signatureType">The type of signature to use</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignature(
Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret,
string httpMethod, string timeStamp, string nonce, SignatureTypes signatureType,
string verifier,
out string normalizedUrl, out string normalizedRequestParameters)
{
normalizedUrl = null;
normalizedRequestParameters = null;
switch (signatureType)
{
case SignatureTypes.PLAINTEXT:
return HttpUtility.UrlEncode(string.Format("{0}&{1}", consumerSecret, tokenSecret));
case SignatureTypes.HMACSHA1:
string signatureBase =
GenerateSignatureBase(
url, consumerKey, token, tokenSecret,
httpMethod, timeStamp, nonce, HMACSHA1SignatureType, verifier,
out normalizedUrl, out normalizedRequestParameters);
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret)));
return GenerateSignatureUsingHash(signatureBase, hmacsha1);
case SignatureTypes.RSASHA1:
throw new NotImplementedException();
default:
throw new ArgumentException("Unknown signature type", "signatureType");
}
}
/// <summary>
/// Generate the timestamp for the signature
/// </summary>
/// <returns></returns>
public virtual string GenerateTimeStamp()
{
// Default implementation of UNIX time of the current UTC time
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
/// <summary>
/// Generate a nonce
/// </summary>
/// <returns></returns>
public virtual string GenerateNonce()
{
// Just a simple implementation of a random number between 123400 and 9999999
return random.Next(123400, 9999999).ToString();
}
}
}
// Copyright (c) 2009, Hiroshi Tsujimura
// Some rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of watcher.moe-nifty.com nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Web;
using System.Collections.Specialized;
using System.Text;
namespace OAuth
{
public class OAuthJaiku : OAuthBase
{
public enum Method { GET, POST };
public const string REQUEST_TOKEN = "http://www.jaiku.com/api/request_token";
public const string AUTHORIZE = "http://www.jaiku.com/api/authorize";
public const string ACCESS_TOKEN = "http://www.jaiku.com/api/access_token";
private string _consumerKey = "";
private string _consumerSecret = "";
private string _token = "";
private string _tokenSecret = "";
#region Properties
public string ConsumerKey
{
get
{
return _consumerKey;
}
set { _consumerKey = value; }
}
public string ConsumerSecret
{
get
{
return _consumerSecret;
}
set { _consumerSecret = value; } // modified, 7 May 2010
}
public string Token { get { return _token; } set { _token = value; } }
public string TokenSecret { get { return _tokenSecret; } set { _tokenSecret = value; } }
#endregion
/// <summary>
/// Get the link to Jaiku's authorization page for this application.
/// </summary>
/// <returns>The url with a valid request token, or a null string.</returns>
public string AuthorizationLinkGet()
{
string ret = null;
string response = oAuthWebRequest(Method.GET, REQUEST_TOKEN, String.Empty);
if (response.Length > 0)
{
//response contains token and token secret. We only need the token.
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs["oauth_token"] != null)
{
ret = AUTHORIZE + "?oauth_token=" + qs["oauth_token"];
this.Token = qs["oauth_token"]; /* {@@} */
}
if (qs["oauth_token_secret"] != null) /* {@@} */
{ /* {@@} */
this.TokenSecret = qs["oauth_token_secret"]; /* {@@} */
} /* {@@} */
ret += "&perms=write"; /* {@@} */
}
return ret;
}
/// <summary>
/// Exchange the request token for an access token.
/// </summary>
public void AccessTokenGet()
{
string response = oAuthWebRequest(Method.GET, ACCESS_TOKEN, String.Empty);
if (response.Length > 0)
{
//Store the Token and Token Secret
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs["oauth_token"] != null)
{
this.Token = qs["oauth_token"];
}
if (qs["oauth_token_secret"] != null)
{
this.TokenSecret = qs["oauth_token_secret"];
}
}
}
/// <summary>
/// Submit a web request using oAuth.
/// </summary>
/// <param name="method">GET or POST</param>
/// <param name="url">The full url, including the querystring.</param>
/// <param name="postData">Data to post (querystring format)</param>
/// <returns>The web server response.</returns>
public string oAuthWebRequest(Method method, string url, string postData)
{
string outUrl = "";
string querystring = "";
string ret = "";
//Setup postData for signing.
//Add the postData to the querystring.
if (method == Method.POST)
{
if (postData.Length > 0)
{
//Decode the parameters and re-encode using the oAuth UrlEncode method.
NameValueCollection qs = HttpUtility.ParseQueryString(postData);
postData = "";
foreach (string key in qs.AllKeys)
{
if (postData.Length > 0)
{
postData += "&";
}
qs[key] = HttpUtility.UrlDecode(qs[key]);
qs[key] = this.UrlEncode(qs[key], Encoding.GetEncoding("utf-8")); /* {@@} */
postData += key + "=" + qs[key];
}
if (url.IndexOf("?") > 0)
{
url += "&";
}
else
{
url += "?";
}
url += postData;
}
}
Uri uri = new Uri(url);
string nonce = this.GenerateNonce();
string timeStamp = this.GenerateTimeStamp();
//Generate Signature
string sig = this.GenerateSignature(uri,
this.ConsumerKey,
this.ConsumerSecret,
this.Token,
this.TokenSecret,
method.ToString(),
timeStamp,
nonce,
out outUrl,
out querystring);
querystring += "&oauth_signature=" + HttpUtility.UrlEncode(sig);
//Convert the querystring to postData
if (method == Method.POST)
{
postData = querystring;
querystring = "";
}
if (querystring.Length > 0)
{
outUrl += "?";
}
if (method == Method.POST) /* {@@} */
{ /* {@@} */
Encoding encode = Encoding.GetEncoding("utf-8"); /* {@@} */
byte[] reqData = encode.GetBytes(postData); /* {@@} */
ret = Utility.PostWebPage( /* {@@} */
outUrl + querystring, reqData, /* {@@} */
"application/x-www-form-urlencoded", /* {@@} */
encode); /* {@@} */
} /* {@@} */
else /* {@@} */
{ /* {@@} */
ret = Utility.GetWebPage(outUrl + querystring); /* {@@} */
} /* {@@} */
return ret;
}
}
}
// Copyright (c) 2009, 2010, Hiroshi Tsujimura
// Some rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of watcher.moe-nifty.com nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
/* original code from: http://www.voiceoftech.com/swhitley/?p=681 */
using System;
using System.Web;
using System.Collections.Specialized;
using System.Text;
namespace OAuth
{
public class OAuthTwitter : OAuthBase
{
public enum Method { GET, POST };
public const string REQUEST_TOKEN = "http://twitter.com/oauth/request_token";
public const string AUTHORIZE = "http://twitter.com/oauth/authorize";
public const string ACCESS_TOKEN = "http://twitter.com/oauth/access_token";
public const string ACCESS_TOKEN_VIA_XAUTH = "https://api.twitter.com/oauth/access_token";
private string _consumerKey = "";
private string _consumerSecret = "";
private string _token = "";
private string _tokenSecret = "";
#region Properties
public string ConsumerKey
{
get
{
return _consumerKey;
}
set { _consumerKey = value; }
}
public string ConsumerSecret
{
get
{
return _consumerSecret;
}
set { _consumerSecret = value; } // modified, 7 May 2010
}
public string Token { get { return _token; } set { _token = value; } }
public string TokenSecret { get { return _tokenSecret; } set { _tokenSecret = value; } }
#endregion
/// <summary>
/// Get the link to Twitter's authorization page for this application.
/// </summary>
/// <returns>The url with a valid request token, or a null string.</returns>
public string AuthorizationLinkGet()
{
string ret = null;
string response = oAuthWebRequest(Method.GET, REQUEST_TOKEN, String.Empty);
if (response.Length > 0)
{
//response contains token and token secret. We only need the token.
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs["oauth_token"] != null)
{
ret = AUTHORIZE + "?oauth_token=" + qs["oauth_token"];
this.Token = qs["oauth_token"]; /* {@@} */
}
if (qs["oauth_token_secret"] != null) /* {@@} */
{ /* {@@} */
this.TokenSecret = qs["oauth_token_secret"]; /* {@@} */
} /* {@@} */
}
return ret;
}
public void AccessTokenGet(string username, string password)
{
string param = "x_auth_mode=client_auth&" +
"x_auth_username=" + username + "&" +
"x_auth_password=" + password;
string response = oAuthWebRequest(Method.POST, ACCESS_TOKEN_VIA_XAUTH, param);
TokenGet(response);
}
/// <summary>
/// Exchange the request token for an access token.
/// </summary>
public void AccessTokenGet(string verifier)
{
string response = oAuthWebRequest(Method.GET, ACCESS_TOKEN, verifier, String.Empty);
TokenGet(response);
}
public void TokenGet(string response)
{
if (response.Length > 0)
{
//Store the Token and Token Secret
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs["oauth_token"] != null)
{
this.Token = qs["oauth_token"];
}
if (qs["oauth_token_secret"] != null)
{
this.TokenSecret = qs["oauth_token_secret"];
}
}
}
/// <summary>
/// Submit a web request using oAuth.
/// </summary>
/// <param name="method">GET or POST</param>
/// <param name="url">The full url, including the querystring.</param>
/// <param name="postData">Data to post (querystring format)</param>
/// <returns>The web server response.</returns>
public string oAuthWebRequest(Method method, string url, string postData)
{
return oAuthWebRequest(method, url, null, postData);
}
public string oAuthWebRequest(Method method, string url, string verifier, string postData)
{
string outUrl = "";
string querystring = "";
string ret = "";
//Setup postData for signing.
//Add the postData to the querystring.
if (method == Method.POST)
{
if (postData.Length > 0)
{
//Decode the parameters and re-encode using the oAuth UrlEncode method.
NameValueCollection qs = HttpUtility.ParseQueryString(postData);
postData = "";
foreach (string key in qs.AllKeys)
{
if (postData.Length > 0)
{
postData += "&";
}
qs[key] = HttpUtility.UrlDecode(qs[key]);
// qs[key] = this.UrlEncode(qs[key]); // <- not working in multibyte characters
qs[key] = this.UrlEncode(qs[key], Encoding.GetEncoding("utf-8")); /* {@@} */
postData += key + "=" + qs[key];
}
if (url.IndexOf("?") > 0)
{
url += "&";
}
else
{
url += "?";
}
url += postData;
}
}
Uri uri = new Uri(url);
string nonce = this.GenerateNonce();
string timeStamp = this.GenerateTimeStamp();
//Generate Signature
string sig;
if (url.StartsWith(ACCESS_TOKEN_VIA_XAUTH))
sig = this.GenerateSignature(uri,
this.ConsumerKey,
this.ConsumerSecret,
null,
null,
method.ToString(),
timeStamp,
nonce,
null,
out outUrl,
out querystring);
else
sig = this.GenerateSignature(uri,
this.ConsumerKey,
this.ConsumerSecret,
this.Token,
this.TokenSecret,
method.ToString(),
timeStamp,
nonce,
verifier,
out outUrl,
out querystring);
querystring += "&oauth_signature=" + HttpUtility.UrlEncode(sig);
//Convert the querystring to postData
/*
if (method == Method.POST)
{
postData = querystring;
querystring = "";
}
*/
if (querystring.Length > 0)
{
outUrl += "?";
}
if (method == Method.POST) /* {@@} */
ret = Utility.PostWebPage( /* {@@} */
outUrl + querystring, null, /* {@@} */
"application/x-www-form-urlencoded", /* {@@} */
Encoding.GetEncoding("utf-8")); /* {@@} */
else /* {@@} */
ret = Utility.GetWebPage(outUrl + querystring); /* {@@} */
return ret;
}
}
}
// Copyright (c) 2008, 2009, Hiroshi Tsujimura
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of watcher.moe-nifty.com nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
namespace OAuth
{
class Utility
{
#region HTTP通信関連
#region 指定Webページの取得
public static string GetWebPage(string url)
{
return GetWebPage(url, (CookieContainer)null);
}
public static string GetWebPage(string url, CookieContainer cc)
{
return GetWebPage(url, "", cc);
}
public static string GetWebPage(string url, Encoding encode, CookieContainer cc)
{
return GetWebPage(url, "", encode, cc, false, null, null);
}
public static string GetWebPage(string url, string wsse, CookieContainer cc)
{
return GetWebPage(url, wsse, cc, false);
}
public static string GetWebPage(string url, string wsse, CookieContainer cc, bool silent)
{
return GetWebPage(url, wsse, cc, silent, null, null);
}
public static string GetWebPage(
string url, string wsse, CookieContainer cc, bool silent, string username, string password)
{
Encoding encode = Encoding.GetEncoding("utf-8");
return GetWebPage(url, wsse, encode, cc, silent, username, password);
}
public static string GetWebPage(
string url, string wsse, Encoding encode, CookieContainer cc, bool silent,
string username, string password)
{
string result = "";
// 指定Webページを取得
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
// request.UserAgent = UserAgent;
if (wsse != null && wsse != "")
request.Headers.Add("X-WSSE: " + wsse);
if (cc != null)
request.CookieContainer = cc;
if (username != null && username != "" &&
password != null && password != "")
request.Credentials = new NetworkCredential(username, password);
ServicePoint currentServicePoint = request.ServicePoint;
if (currentServicePoint != null)
currentServicePoint.Expect100Continue = false;
request.AllowAutoRedirect = true;
HttpWebResponse response = SendRequest(request, silent);
if (response == null)
return result;
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, encode);
while (!readStream.EndOfStream)
{
result += readStream.ReadLine();
}
readStream.Close();
response.Close();
return result;
}
#endregion
#region 指定Webページにリクエストを送信
public static string PostWebPage(string postURL, byte[] postData, string mimeType, Encoding encode)
{
return PostWebPage(postURL, postData, mimeType, encode, null);
}
public static string PostWebPage(
string postURL, byte[] postData, string mimeType, Encoding encode, CookieContainer cc)
{
return PostWebPage(postURL, postData, mimeType, "", encode, cc);
}
public static string PostWebPage(
string postURL, byte[] postData, string mimeType, string wsse, Encoding encode, CookieContainer cc)
{
return PostWebPage(postURL, postData, mimeType, wsse, encode, cc, "POST");
}
public static string PostWebPage(
string postURL, byte[] postData, string mimeType, string wsse, Encoding encode, CookieContainer cc,
string method)
{
return PostWebPage(postURL, postData, mimeType, wsse, encode, cc, method, false);
}
public static string PostWebPage(
string postURL, byte[] postData, string mimeType, string wsse, Encoding encode, CookieContainer cc,
string method, bool silent)
{
return PostWebPage(postURL, postData, mimeType, wsse, encode, cc, method, silent, null, null);
}
public static string PostWebPage(
string postURL, byte[] postData, string mimeType, string wsse, Encoding encode, CookieContainer cc,
string method, bool silent, string username, string password)
{
string location = null;
return PostWebPage(postURL, postData, mimeType, wsse, encode, cc,
method, silent, username, password, true, ref location);
}
public static string PostWebPage(
string postURL, byte[] postData, string mimeType, string wsse, Encoding encode, CookieContainer cc,
string method, bool silent, string username, string password,
bool allowAutoRedirect, ref string location)
{
string result = "";
bool error = false;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postURL);
if (method != null && method != "")
request.Method = method;
else
request.Method = "POST";
// request.UserAgent = UserAgent;
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
if (wsse != null && wsse != "")
{
request.Headers.Add("X-WSSE: " + wsse);
request.Accept = "application/x.atom+xml, application/xml, text/xml, */*";
}
if (cc != null)
request.CookieContainer = cc;
if (username != null && username != "" &&
password != null && password != "")
request.Credentials = new NetworkCredential(username, password);
ServicePoint currentServicePoint = request.ServicePoint;
if (currentServicePoint != null)
currentServicePoint.Expect100Continue = false;
if (mimeType != null && mimeType != "")
request.ContentType = mimeType;
else
request.ContentType = "text/plain";
request.AllowAutoRedirect = true;
if (allowAutoRedirect == false)
request.AllowAutoRedirect = false;
if (postData != null)
{
try
{
request.ContentLength = postData.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
reqStream.Close();
}
catch
{
error = true;
}
}
else
request.ContentLength = 0;
if (!error)
{
HttpWebResponse response = SendRequest(request, silent);
if (response != null)
{
if (response.StatusCode == HttpStatusCode.Found ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Ambiguous)
{
string locationURL = "";
foreach (string value in response.Headers)
{
if (value == "Location")
{
locationURL = response.Headers[HttpResponseHeader.Location];
break;
}
}
if (locationURL != "")
{
if (location != null)
location = locationURL;
else
{
response.Close();
return GetWebPage(locationURL, wsse, encode, cc, silent,
username, password);
}
}
}
Stream receiveStream = response.GetResponseStream();
if (receiveStream != null)
{
StreamReader readStream = new StreamReader(receiveStream, encode);
if (readStream != null)
{
try
{
while (!readStream.EndOfStream)
{
result += readStream.ReadLine();
}
}
catch (Exception ee)
{
Console.WriteLine("PostWebPage: " + ee.Message);
}
readStream.Close();
}
}
response.Close();
}
}
return result;
}
#endregion
#region HTTPリクエストを送信
public static HttpWebResponse SendRequest(HttpWebRequest request)
{
return SendRequest(request, false);
}
public static HttpWebResponse SendRequest(HttpWebRequest request, bool silent)
{
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception ee)
{
if (!silent)
{
string url = request.Address.ToString();
if (ee.GetType() == typeof(WebException))
{
bool done = false;
WebException we = (WebException)ee;
if (url.Contains("oauth_consumer_key") &&
we.Response != null &&
((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Unauthorized)
{ // 401 error
if (url.StartsWith("http://twitter.com"))
done = true;
}
if (!done)
{
string statusString = we.Status.ToString();
if (we.Status == WebExceptionStatus.ProtocolError && we.Response != null)
Console.WriteLine(
url + ": " +
((HttpWebResponse)we.Response).StatusCode + "\r\n" +
"[" + ((HttpWebResponse)we.Response).StatusDescription + "]");
else
Console.WriteLine(url + ": " + statusString);
}
}
else
Console.WriteLine(url + ": " + ee.Message);
}
response = null;
}
return response;
}
#endregion
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment