Oauth2认证以及新浪微博开放平台应用

1、OAuth2.0概述

大部分API的访问如发表微博、获取私信,关注都须要用户身份,目前新浪微博开放平台用户身份鉴权有OAuth2.0和Basic Auth(仅用于应用所属开发者调试接口),新版接口也仅支持这两种方式。OAuth2.0较1.0相比整个受权验证流程更简单更安全,也是将来最主要的用户身份验证和受权方式。 关于OAuth2.0协议受权流程查看OAuth2.0受权流程 ,其中Client指第三方应用,Resource Owner指用户,Authorization Server是咱们的受权服务器,Resource Server是API服务器。php

参考连接:http://blog.unvs.cn/archives/oauth-qq2.0-developer.html 以及新浪微博开放平台和新浪微博CodeProject开源项目html

开发者能够先浏览OAuth2.0的接口文档,熟悉OAuth2的接口及参数的含义,而后咱们根据应用场景各自说明如何使用OAuth2.0。web

OAuth2 接口文档api

接口 说明
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

 

2、OAuth2.0 新浪受权页浏览器

一、首先要获取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给替换掉。app

 

二、受权页面异步

下面的是提示微博登录的界面,登录后提供第三方网站受权访问你在新浪微博帐号上的资源函数

三、受权访问页面

 

四、新浪官方网站提供API测试工具,用来测试客户端构造的参数是否正确

五、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,进行请求,获取用户受权资源信息

相关文章
相关标签/搜索