欢迎光临

木子屋

标题: 新浪微博开放平台OAuth授权简单示例[C#]

作者: dnawo

日期: 2011-03-17 04:33 PM

分类: Web编程

内容: Default.aspx：
复制内容到剪贴板 程序代码<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Button ID="btnRequestToken" runat="server" onclick="btnRequestToken_Click"
Text="OAuth测试" />

</div>
</form>
</body>
</html>
Default.aspx.cs：
复制内容到剪贴板 程序代码using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
private const string REQUEST_TOKEN = "http://api.t.sina.com.cn/oauth/request_token";
private const string AUTHORIZE = "http://api.t.sina.com.cn/oauth/authorize";
private const string ACCESS_TOKEN = "http://api.t.sina.com.cn/oauth/access_token";
private string oauth_consumer_key = "2098100000";
private string oauth_consumer_secret = "bc4ffde96c65371390fde0000000000";
public string oauth_token
{
get { return Session["oauth_token"] + ""; }
set { Session["oauth_token"] = value; }
}
public string oauth_token_secret
{
get { return Session["oauth_token_secret"] + ""; }
set { Session["oauth_token_secret"] = value; }
}
/// <summary>
/// 开始
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnRequestToken_Click(object sender, EventArgs e)
{
if (Request_Token())//第一步：获取未授权的Request_Token
Authorize();//第二步：获取用户授权的Request_Token
}
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["oauth_token"] != null && Request.QueryString["oauth_verifier"] != null)
{
if (Access_Token())//第三步：获取Access_Token
{
Response.Write("oauth_token=" + oauth_token + "<br/>");
Response.Write("oauth_token_secret=" + oauth_token_secret + "<br/>");
}
}
}
/// <summary>
/// 第一步：获取未授权的Request_Token
/// </summary>
/// <returns></returns>
protected bool Request_Token()
{
SortedList<string, string> parameters = new SortedList<string, string>();
parameters.Add("oauth_consumer_key", oauth_consumer_key);
parameters.Add("oauth_signature_method", "HMAC-SHA1");
parameters.Add("oauth_timestamp", GenerateTimeStamp());
parameters.Add("oauth_nonce", GenerateNonce());
parameters.Add("oauth_version", "1.0");
parameters.Add("oauth_signature", HMACSHA1(oauth_consumer_secret, "", ListToSignatureBaseString("GET", REQUEST_TOKEN, parameters)));
//oauth_token=d21ec5d68d12d19367cf2be1a22b5ee3&oauth_token_secret=f879974707aeac8629c4cd93cd821c29
string result = HttpGet(REQUEST_TOKEN, ListToQueryString(parameters));
if (result.IndexOf("&oauth_token_secret=") != -1)
{
Dictionary<string, string> parameters2 = UrlParse(result);
oauth_token = parameters2["oauth_token"];
oauth_token_secret = parameters2["oauth_token_secret"];
return true;
}
else
{
return false;
}
}
/// <summary>
/// 第二步：获取用户授权的Request_Token
/// </summary>
protected void Authorize()
{
SortedList<string, string> parameters = new SortedList<string, string>();
parameters.Add("oauth_token", oauth_token);
parameters.Add("oauth_callback", "http://127.0.0.1/sina");
//url?oauth_token=d21ec5d68d12d19367cf2be1a22b5ee3&oauth_verifier=815310
Response.Redirect(AUTHORIZE + "?" + ListToQueryString(parameters));
}
/// <summary>
/// 第三步：获取Access_Token
/// </summary>
protected bool Access_Token()
{
SortedList<string, string> parameters = new SortedList<string, string>();
parameters.Add("oauth_consumer_key", oauth_consumer_key);
parameters.Add("oauth_token", Request.QueryString["oauth_token"]);
parameters.Add("oauth_signature_method", "HMAC-SHA1");
parameters.Add("oauth_timestamp", GenerateTimeStamp());
parameters.Add("oauth_nonce", GenerateNonce());
parameters.Add("oauth_version", "1.0");
parameters.Add("oauth_verifier", Request.QueryString["oauth_verifier"]);
parameters.Add("oauth_signature", HMACSHA1(oauth_consumer_secret, oauth_token_secret, ListToSignatureBaseString("POST", ACCESS_TOKEN, parameters)));
//oauth_token=57a8c34e597352e0e41cd6d59eddd8c0&oauth_token_secret=8aeee485bd7aac111dc4d90778b94954&user_id=1893854887
string result = HttpPost(ACCESS_TOKEN, ListToQueryString(parameters));
if (result.IndexOf("&oauth_token_secret=") != -1)
{
Dictionary<string, string> parameters2 = UrlParse(result);
oauth_token = parameters2["oauth_token"];
oauth_token_secret = parameters2["oauth_token_secret"];
return true;
}
else
{
return false;
}
}
#region 公共函数...
public string UrlEncode(string value)
{
StringBuilder result = new StringBuilder();
string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
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();
}
public string ListToSignatureBaseString(string httpMethod, string base_uri, SortedList<string, string> parameters)
{
StringBuilder sb = new StringBuilder();
sb.Append(UrlEncode(httpMethod) + "&");
sb.Append(UrlEncode(base_uri) + "&");
foreach (KeyValuePair<string, string> item in parameters)
{
sb.Append(UrlEncode(item.Key) + "%3D" + UrlEncode(item.Value) + "%26");
}
int len = sb.ToString().Length;
return sb.ToString().Substring(0, len - 3);
}
public string ListToQueryString(SortedList<string, string> parameters)
{
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> item in parameters)
{
sb.Append('&' + UrlEncode(item.Key) + "=" + UrlEncode(item.Value));
}
return sb.ToString().Substring(1);
}
public string HMACSHA1(string consumer_secret, string oauth_token_secret, string signaturebasestring)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = Encoding.ASCII.GetBytes(consumer_secret + "&" + oauth_token_secret);
byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(signaturebasestring);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
string signature = Convert.ToBase64String(hashBytes);
return signature;
}
public string GenerateTimeStamp()
{
return (DateTime.Now.Ticks - DateTime.Parse("1970-01-01 00:00:00").Ticks) / 10000000 + "";
}
public string GenerateNonce()
{
return DateTime.Now.Ticks.ToString();
}
public Dictionary<string, string> UrlParse(string query)
{
Dictionary<string, string> result = new Dictionary<string, string>();
string[] parameters = query.Split('&');
for (int i = 0; i < parameters.Length; i++)
{
result.Add(parameters[i].Split('=')[0], parameters[i].Split('=')[1]);
}
return result;
}
public string HttpPost(string action, string parmString)
{
try
{
Encoding encoding = Encoding.GetEncoding("utf-8");
Uri uri = new Uri(action);
byte[] paramBytes = encoding.GetBytes(parmString);
WebRequest webRequest = WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
using (Stream stream = webRequest.GetRequestStream())
{
stream.Write(paramBytes, 0, paramBytes.Length);
}
WebResponse webResponse = webRequest.GetResponse();
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), encoding))
{
return reader.ReadToEnd();
}
}
catch (Exception ex)
{
return ex.Message;
}
}
public string HttpGet(string action, string parmString)
{
try
{
Encoding encoding = Encoding.GetEncoding("utf-8");
Uri uri = new Uri(string.Format("{0}?{1}", action, parmString));
WebRequest webRequest = WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "GET";
WebResponse webResponse = webRequest.GetResponse();
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), encoding))
{
return reader.ReadToEnd();
}
}
catch (Exception ex)
{
return ex.Message;
}
}
#endregion
}

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.746 ms

返回

标题: 新浪微博开放平台OAuth授权简单示例[C#]

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.746 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.902 ms

返回