Oauth Learning (1) -- Sina Weibo oauth authorization

Source: Internet
Author: User
Tags hmac oauth
Recently, open platforms have become very popular. Internet companies have launched their own open platforms, followed by the popular openid. oauth has become the main technology for authentication and authorization. This document takes logon to Sina Weibo for authorization to obtain user data as an example to briefly study the use of oauth. (Oauth wiki ). Currently, there are many open-source oauth frameworks on. NET. For example:
Dotnetopenauth (I don't know what's going on, this website is not very good recently)
Oauth. net
Devdefined. oauth
I checked the source code and help documentation, and compared it. I chose devdefined. oauth as the oauth framework in this example, because it is easy to get started.
(PS: the latest version of oauth is 2.0, but currently most websites only support 1.0)

Let's take a look at the oauth authorization flowchart:

For help, define three roles: 1. End User, 2. Application (consumer), and 3. Service (Authorizer ). The main process for defining oauth is as follows:
(1) When [user] uses [application], the [application] prompts [user] That requires authorization. [application] first obtains the requesttoken from [SERVICE ].
(2) The [application] jumps to the [SERVICE] end with the requesttoken and the specified callback, and enables the [user] to enter the user name and password for authorization.
(3) After the authorization is successful, the [SERVICE] side will jump to the callback page provided by the [application], and the [application] will get: accesstoken
(4) Next, the [application] uses the accesstoken to obtain various user data on the [SERVICE] from the [SERVICE] end.
Okay. Let's take a look at how to use Sina Weibo's oauth. First of all, you need to apply for an appkey and appsecret for a Sina app.

Sina oauth official documentation: http://open.weibo.com/wiki/index.php/Oauth

[Preparation]
1. Add devdefined. oauth. dll
2. Define requesturl, accessurl, userauthorizeurl, appkey, and appsecret in Project Settings.


[Application page portal]

Press click to obtain the requesttoken to jump to the Sina authorization page:

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);}

Request content intercepted by fiddler:
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] is the application key applied for, [Signature] is based on baseurl using the HMAC-SHA1 and sinaappsecret generated signature. The subsequent requests are similar, whether using get or post.


After authorization, go to the callback page: Here callback is developed using ashx. When callback is requested by the server, oauth_token and oauth_verifier can be obtained from the request.

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 =>{ // After the accesstoken is exchanged, user_id is returned and user_id = RegEx is obtained using the regular expression. match (body, "user_id = (. *)"). groups [1]. value ;}; itoken accesen en = session. exchangerequesttokenforaccesstoken (requesttoken, oauthverifier); context. session [requesttokenstring] = NULL; context. session ["acess_token"] = accesstoken; context. session ["user_id"] = user_id; context. response. redirect ("welcome. aspx ");}}

On the welcome. ASPX page, obtain the user's personal information:

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; // appkey var showuserurl = string is not required when oauth is used. 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 }}}

Use oauth_accesstoken to access the json api of http://api.t.sina.com.cn/users/show/%0%.json ({0} replaced by user ID) request, and bind it to the detailform control with json.net deserialization.
Code download: http://download.csdn.net/source/3482263

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.