一、OAuth2.0概述
大部分API的访问如发表微博、获取私信,关注都需要用户身份,目前新浪微博开放平台用户身份鉴权有OAuth2.0和Basic Auth(仅用于应用所属开发者调试接口),新版接口也仅支持这两种方式。OAuth2.0较1.0相比整个授权验证流程更简单更安全,也是未来最主要的用户身份验证和授权方式。 关于OAuth2.0协议授权流程查看OAuth2.0授权流程 ,其中Client指第三方应用,Resource Owner指用户,Authorization Server是我们的授权服务器,Resource Server是API服务器。
参考链接:http://blog.unvs.cn/archives/oauth-qq2.0-developer.html 以及新浪微博开放平台和新浪微博CodeProject开源项目
开发者可以先浏览OAuth2.0的接口文档,熟悉OAuth2的接口及参数的含义,然后我们根据应用场景各自说明如何使用OAuth2.0。
OAuth2 接口文档
接口 | 说明 |
---|---|
OAuth2/authorize | 请求用户授权Token |
OAuth2/access_token | 获取授权过的Access Token |
OAuth2/get_token_info | 授权信息查询接口 |
OAuth2/revokeoauth2 | 授权回收接口 |
OAuth2/get_oauth2_token | OAuth1.0的Access Token更换至OAuth2.0的Access Token |
二、OAuth2.0 新浪授权页
1、首先要获取appKey 和 appSecret,这个获取的方法可以从新浪微博新手指南 根据步骤一步一步的获取到。callBack地址这里采用默认的:https://api.weibo.com/oauth2/default.html,采用的是网站接入方式。下面是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 appkey = "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(appkey,appsecret,callBack);
21.
22. 模拟登录
23. //string username = "xxxxxxxx@163.com";
24. //string password = "xxxxxxx";
25. //oauth.ClientLogin(username, password); //模拟登录下,没啥好说的,你也可以改成标准登录。
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("填写浏览器地址中的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("开始发送异步请求...");
51.
52. //例子1:异步获取用户的ID
53. //demo的运行环境是.net 4.0,下面展示的这种方法在2.0及以上版本环境下有效,3.0以上可以用lambda表达式来简化delegate的蛋疼写法,请看下面的例子。
54. Sina.AsyncInvoke<string>(
55. //第一个代理中编写调用API接口的相关逻辑
56. delegate()
57. {
58. Console.WriteLine("发送请求来获得用户ID...");
59. System.Threading.Thread.Sleep(8000); //等待8秒
60. return Sina.API.Entity.Account.GetUID();
61. },
62. //第二个代理为回调函数,异步完成后将自动调用这个函数来处理结果。
63. delegate(AsyncCallback<string> callback)
64. {
65. if (callback.IsSuccess)
66. {
67. Console.WriteLine("获取用户ID成功,ID:{0}", callback.Data);
68. }
69. else
70. {
71. Console.WriteLine("获取用户ID失败,异常:{0}", callback.Error);
72. }
73. }
74. );
75.
76. //列子2:获取公共微博列表
77. //2.0以上用lambda来写,方便不是一点点
78. Sina.AsyncInvoke<NetDimension.Weibo.Entities.status.Collection>(() =>
79. {
80. //获取微博,接口调用,返回值是个NetDimension.Weibo.Entities.status.Collection,所以泛型T为NetDimension.Weibo.Entities.status.Collection
81. Console.WriteLine("发送请求来获得公共微博列表...");
82. return Sina.API.Entity.Statuses.PublicTimeline();
83. //return Sina.API.Entity.Statuses.RepostTimeline;
84. }, (callback) =>
85. {
86. if (callback.IsSuccess)
87. {
88. //异步完成后处理结果,result就是返回的结果,类型就是泛型所指定的NetDimension.Weibo.Entities.status.Collection
89. Console.WriteLine("获得公共微博列表成功,现在公共频道发微博的人都是他们:");
90. foreach (var status in callback.Data.Statuses)
91. {
92. if (status.User != null)
93. Console.WriteLine(status.User.ScreenName + " ");//打印公共微博发起人的姓名
94. }
95. Console.WriteLine();
96. }
97. else
98. {
99. Console.WriteLine("获取用户ID失败,异常:{0}", callback.Error);
100. }
101.
102. });
103.
104.
105. Console.WriteLine("已发送所有异步请求。等待异步执行完成...");
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(appKey,appSecret,Url.Action("LoginSinaResult", "MySelf", null, "http"));
//第一步获取新浪授权页面的地址
var oauthUrl = oauth.GetAuthorizeURL();
return Redirect(oauthUrl);
}
public ActionResult LoginSinaResult(string code)
{
var oauth = new NetDimension.Weibo.OAuth(appKey, 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("您尚未注册");
}
}
}
如果要运行上述程序的话,需要把Appkey和Appsecret给替换掉。
2、授权页面
下面的是提示微博登陆的界面,登陆后提供第三方网站授权访问你在新浪微博账号上的资源
3、授权访问页面
4、新浪官方网站提供API测试工具,用来测试客户端构造的参数是否正确
5、Oauth2.0运行流程图
第一步:首先直接跳转至用户授权地址,即图示 Request User Url ,提示用户进行登录,并给予相关资源授权,得到唯一的Auth code,这里注意的是code只有10分钟的有效期,对于安全考虑,相对于OAuth1.0省了一步获取临时的Token,并且有效期也进行了控制,比1.0认证简化了很多,并安全一些; 第二步:得到授权code后,这一步就是请求access token,通过 图示 Request access url ,生成得到数据Token; 第三步:通过Access Token请求OpenID,openid是用户在此平台的唯一标识,通过 图示 Request info url 请求,然后得到OpenID; 第四步:通过第二步得到的数据Token、第三步得到的OpenID及相关API,进行请求,获取用户授权资源信息