【准备】
1. 添加 DevDefined.OAuth.dll
2. 将 RequestUrl, AccessUrl, UserAuthorizeUrl 以及 AppKey, AppSecret 定义在 Project Settings 中
【应用页面入口】
按下 Click 获得 RequestToken 跳转到新浪授权页面:
protected void oauthRequest_Click(object sender, EventArgs e) { var session = OAuthSessionFactory.CreateSession(); var requestToken = session.GetRequestToken(); if (string.IsNullOrEmpty(requestToken.Token)) { throw new Exception("The request token was null or empty"); } Session[requestToken.Token] = requestToken; var callback = "http://localhost:" + HttpContext.Current.Request.Url.Port + "/Callback.ashx"; var authorizationUrl = session.GetUserAuthorizationUrlForToken(requestToken, callback); Response.Redirect(authorizationUrl, true); }
Fiddler 拦截的Request内容:
GET http://api.t.sina.com.cn/oauth/request_token?oauth_callback=oob&oauth_nonce=99119f7f-ace7-45d4-86b5-31ddd092ca86&oauth_consumer_key=[SinaAppKey]&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1311492533&oauth_version=1.0&oauth_signature=[Signature] HTTP/1.1
说明:[SinaAppKey] 是申请的应用程序Key, [Signature]是根据 BaseUrl 使用 HMAC-SHA1 和 SinaAppSecret 生成的签名。后面的请求无论是用 GET 还是 POST,都类似。
public partial class Callback : System.Web.IHttpHandler, System.Web.SessionState.IRequiresSessionState { public void ProcessRequest(System.Web.HttpContext context) { var session = OAuthSessionFactory.CreateSession(); var requestTokenString = context.Request["oauth_token"]; var oauthVerifier = context.Request["oauth_verifier"]; var user_id = ""; var requestToken = (IToken)context.Session[requestTokenString]; session.ResponseBodyAction = body => { // 交换完AccessToken后,会返回user_id,用正则表达式取出 user_id = Regex.Match(body, "user_id=(.*)").Groups[1].Value; }; IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken, oauthVerifier); context.Session[requestTokenString] = null; context.Session["acess_token"] = accessToken; context.Session["user_id"] = user_id; context.Response.Redirect("Welcome.aspx"); } }在 Welcome.aspx 页面中,获取用户的个人信息:
public partial class Weclome : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { IToken accessToken = Session["acess_token"] as IToken; var userId = Session["user_id"] as string; // 使用OAuth时不用传AppKey var showUserUrl = string.Format("http://api.t.sina.com.cn/users/show/{0}.json", userId); var session = OAuthSessionFactory.CreateSession(); session.AccessToken = accessToken; try { var resp = session.Request().Get().ForUrl(showUserUrl).SignWithToken().ToWebResponse(); using (var sr = new StreamReader(resp.GetResponseStream())) { var json = sr.ReadToEnd(); var userInfo = JsonConvert.DeserializeObject<SinaWeiboUser>(json); detailUserInfo.DataSource = new List<SinaWeiboUser> { userInfo }; detailUserInfo.DataBind(); } } catch (WebException webEx) { var resp = (HttpWebResponse)webEx.Response; using (var sr = new StreamReader(resp.GetResponseStream())) { Response.Write(sr.ReadToEnd()); } } #region By WebClient Request //var client = new WebClient(); //var customerOAuthContext = new OAuthConsumerContext //{ // ConsumerKey = Properties.Settings.Default.SinaAppKey, // ConsumerSecret = Properties.Settings.Default.SinaAppSecret, // SignatureMethod = SignatureMethod.HmacSha1, // UseHeaderForOAuthParameters = true, //}; //var oauthContext = new OAuthContext() //{ // RawUri = new Uri(showUserUrl), // RequestMethod = "GET", //}; //customerOAuthContext.SignContextWithToken(oauthContext, accessToken); //var token = string.Format(",oauth_token=\"{0}\"", accessToken.Token); //client.Headers[Parameters.OAuth_Authorization_Header] = oauthContext.GenerateOAuthParametersForHeader() + token; //client.Encoding = System.Text.Encoding.UTF8; //var json = client.DownloadString(showUserUrl); //var userInfo = JsonConvert.DeserializeObject<SinaWeiboUser>(json); //detailUserInfo.DataSource = new List<SinaWeiboUser> { userInfo }; //detailUserInfo.DataBind(); #endregion } } }用 oauth_accesstoken 访问 http://api.t.sina.com.cn/users/show/{0}.json ({0}用用户Id替换)请求json的api,用json.net 反序列化绑定到 DetailForm 控件上。