使用新浪微博開(kāi)放平臺api同步微博內容至自己網(wǎng)站(OAuth2.0協(xié)議授權流程查看/access_token獲取)
優(yōu)采云 發(fā)布時(shí)間: 2022-04-18 20:35使用新浪微博開(kāi)放平臺api同步微博內容至自己網(wǎng)站(OAuth2.0協(xié)議授權流程查看/access_token獲取)
一、OAuth2.0 概述
大部分API的訪(fǎng)問(wèn),如發(fā)微博、獲取私信、關(guān)注,都需要用戶(hù)身份。目前新浪微博開(kāi)放平臺用戶(hù)身份認證包括OAuth2.0和Basic Auth(僅用于應用開(kāi)發(fā)Debug接口),新版接口僅支持這兩種方式。與1.0相比,OAuth2.0比整個(gè)授權驗證過(guò)程更簡(jiǎn)單、更安全,也是未來(lái)最重要的用戶(hù)認證授權方式。 OAuth2.0協(xié)議授權流程見(jiàn)OAuth2.0授權流程,其中Client指第三方應用,Resource Owner指用戶(hù),Authorization Server就是我們的授權服務(wù)器,資源服務(wù)器是一個(gè) API 服務(wù)器。
參考鏈接:以及新浪微博開(kāi)放平臺和新浪微博CodeProject開(kāi)源項目
開(kāi)發(fā)者可以先瀏覽OAuth2.0的接口文檔,熟悉OAuth2接口和參數的含義,然后我們會(huì )根據應用場(chǎng)景講解如何使用OAuth2.0 .
OAuth2 接口文檔
接口說(shuō)明
OAuth2/授權
請求用戶(hù)授權令牌
OAuth2/access_token
獲取授權的訪(fǎng)問(wèn)令牌
OAuth2/get_token_info
授權信息查詢(xún)界面
OAuth2/revokeoauth2
授權回收接口
OAuth2/get_oauth2_token
將OAuth的Access Token1.0改為OAuth的Access Token2.0
二、OAuth2.0 新浪授權頁(yè)面
1、第一步,獲取a*敏*感*詞*ey和appSecret。這個(gè)方法可以從新浪微博新手指南一步一步得到。這里使用默認的callBack地址:使用網(wǎng)站訪(fǎng)問(wèn)方式。以下是 C# 示例源代碼(控制臺應用程序):
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05.using NetDimension.Weibo;
06.using System.Net;
07.
08.namespace SinaWeiboTestApp
09.{
10. class Program
11. {
12.
13. static void Main(string[] args)
14. {
15.
16. string a*敏*感*詞*ey = "124543453288";
17. string appsecret = "3a456c5332fd2cb1178338fccb9fa51c";
18. //string callBack = "http://127.0.0.1:3170/WebSite2/Default.aspx";
19. string callBack = "https://api.weibo.com/oauth2/default.html";
20. var oauth = new NetDimension.Weibo.OAuth(a*敏*感*詞*ey,appsecret,callBack);
21.
22. 模擬登錄
23. //string username = "xxxxxxxx@163.com";
24. //string password = "xxxxxxx";
25. //oauth.ClientLogin(username, password); //模擬登錄下,沒(méi)啥好說(shuō)的,你也可以改成標準登錄。
26.
27. //標準登錄
28. var authUrl = oauth.GetAuthorizeURL();
29. //string redirectUrl;
30. //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(authUrl);
31. //request.Referer = authUrl;
32. //request.AllowAutoRedirect = false;
33. //using (WebResponse response = request.GetResponse())
34. //{
35. // redirectUrl = response.Headers["Location"];
36. // redirectUrl = response.ResponseUri.AbsolutePath;
37. //}
38. System.Diagnostics.Process.Start(authUrl);
39. Console.WriteLine("填寫(xiě)瀏覽器地址中的Code參數:");
40. var code = Console.ReadLine();
41. var accessToken = oauth.GetAccessTokenByAuthorizationCode(code);
42. if (!string.IsNullOrEmpty(accessToken.Token))
43. {
44. var sina = new NetDimension.Weibo.Client(oauth);
45. var uid = sina.API.Dynamic.Account.GetUID(); //調用API中獲取UID的方法
46. Console.WriteLine(uid);
47. }
48.
49. var Sina = new Client(oauth);
50. Console.WriteLine("開(kāi)始發(fā)送異步請求...");
51.
52. //例子1:異步獲取用戶(hù)的ID
53. //demo的運行環(huán)境是.net 4.0,下面展示的這種方法在2.0及以上版本環(huán)境下有效,3.0以上可以用lambda表達式來(lái)簡(jiǎn)化delegate的蛋疼寫(xiě)法,請看下面的例子。
54. Sina.AsyncInvoke(
55. //第一個(gè)代理中編寫(xiě)調用API接口的相關(guān)邏輯
56. delegate()
57. {
58. Console.WriteLine("發(fā)送請求來(lái)獲得用戶(hù)ID...");
59. System.Threading.Thread.Sleep(8000); //等待8秒
60. return Sina.API.Entity.Account.GetUID();
61. },
62. //第二個(gè)代理為回調函數,異步完成后將自動(dòng)調用這個(gè)函數來(lái)處理結果。
63. delegate(AsyncCallback callback)
64. {
65. if (callback.IsSuccess)
66. {
67. Console.WriteLine("獲取用戶(hù)ID成功,ID:{0}", callback.Data);
68. }
69. else
70. {
71. Console.WriteLine("獲取用戶(hù)ID失敗,異常:{0}", callback.Error);
72. }
73. }
74. );
75.
76. //列子2:獲取公共微博列表
77. //2.0以上用lambda來(lái)寫(xiě),方便不是一點(diǎn)點(diǎn)
78. Sina.AsyncInvoke(() =>
79. {
80. //獲取微博,接口調用,返回值是個(gè)NetDimension.Weibo.Entities.status.Collection,所以泛型T為NetDimension.Weibo.Entities.status.Collection
81. Console.WriteLine("發(fā)送請求來(lái)獲得公共微博列表...");
82. return Sina.API.Entity.Statuses.PublicTimeline();
83. //return Sina.API.Entity.Statuses.RepostTimeline;
84. }, (callback) =>
85. {
86. if (callback.IsSuccess)
87. {
88. //異步完成后處理結果,result就是返回的結果,類(lèi)型就是泛型所指定的NetDimension.Weibo.Entities.status.Collection
89. Console.WriteLine("獲得公共微博列表成功,現在公共頻道發(fā)微博的人都是他們:");
90. foreach (var status in callback.Data.Statuses)
91. {
92. if (status.User != null)
93. Console.WriteLine(status.User.ScreenName + " ");//打印公共微博發(fā)起人的姓名
94. }
95. Console.WriteLine();
96. }
97. else
98. {
99. Console.WriteLine("獲取用戶(hù)ID失敗,異常:{0}", callback.Error);
100. }
101.
102. });
103.
104.
105. Console.WriteLine("已發(fā)送所有異步請求。等待異步執行完成...");
106.
107. Console.ReadKey(); //阻塞,等待異步調用執行完成
108.
109. }
110.
111. }
112.}
MVC 中的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Myself.Models;
using Myself.Code;
using BLL;
using Lib;
using SpeexToWavToMp3;
using System.Web.Http.Filters;
using Models;
using Webdiyer.WebControls.Mvc;
using System.IO;
namespace Myself.Controllers
{
public class MySelfController : Controller
{
public ActionResult LoginSina()
{
var oauth = new NetDimension.Weibo.OAuth(a*敏*感*詞*ey,appSecret,Url.Action("LoginSinaResult", "MySelf", null, "http"));
//第一步獲取新浪授權頁(yè)面的地址
var oauthUrl = oauth.GetAuthorizeURL();
return Redirect(oauthUrl);
}
public ActionResult LoginSinaResult(string code)
{
var oauth = new NetDimension.Weibo.OAuth(a*敏*感*詞*ey, appSecret, Url.Action("LoginSinaResult", "MySelf", null, "http"));
var oauthToken = oauth.GetAccessTokenByAuthorizationCode(code);
var model = UserHelper.GetAuthorizeInfo(oauthToken.UID, 1);
if (model != null)
{
if (LoginHelper.UserLogin(model.UserID, 1, oauthToken.UID, Request.UserAgent, Request.UserHostAddress, "1", "web"))
{
return RedirectToAction("Index", "Home");
}
else
{
return Content("登錄失敗");
}
}
return Content("您尚未注冊");
}
}
}
如果要運行上述程序,需要更換A*敏*感*詞*ey和Appsecret。
2、授權頁(yè)面
以下是微博登錄提示界面。登錄后,將提供第三方網(wǎng)站授權訪(fǎng)問(wèn)您新浪微博賬號資源
3、授權訪(fǎng)問(wèn)頁(yè)面
4、新浪官方網(wǎng)站提供API測試工具,測試客戶(hù)端構造的參數是否正確
5、Oauth2.0操作流程圖
第一步:首先直接跳轉到用戶(hù)授權地址,即如圖所示的Request User Url,提示用戶(hù)登錄,并授權相關(guān)資源獲取唯一的Auth碼。請注意,該代碼僅在 10 分鐘內有效。 ,出于安全考慮,相比OAuth1.0,它省了一步獲取臨時(shí)Token,而且有效期也可控,比1.0認證簡(jiǎn)單安全多了;第二步:獲取授權碼后,這一步是請求訪(fǎng)問(wèn)令牌,通過(guò)如圖所示的Request access url生成數據令牌; Step 3:通過(guò)Access Token請求一個(gè)OpenID,openid是用戶(hù)在本平臺的唯一標識,通過(guò)如圖所示的Request info url請求,得到OpenID; Step 4:通過(guò)第二步獲取的數據Token,第三步獲取的OpenID及相關(guān)API,請求獲取用戶(hù)授權資源信息
轉載于:





