Oauth authentication for Douban APIs

Source: Internet
Author: User
Tags oauth oauth header

Douban API allows third-party applications to access user data through oauth. Therefore, oauth is the basis of our entire project.

Oauth authentication sounds mysterious, but it is actually quite simple.

Currently, most of the open platforms for large websites use oauth, such as Facebook, Twitter, and Sina Weibo.

Watercress API for oauth certification special instructions: http://www.douban.com/service/apidoc/auth

Before you use oauth authentication, it is necessary to carefully read the document, because there is a slight deviation in the intermediate process, you can not be authenticated successfully, so carefully read the official documentation is the top priority: http://oauth.net/documentation/spec/

If your English is not good enough, you can take a look at the introduction of this Chinese, it is very clear: http://www.supidea.com/post/oauth.aspx

The Google oauth project has provided libraries for various oauth languages: http://code.google.com/p/oauth/

We officially used C # Library: http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs in Google oauth

Because oauth has become a major obstacle for third-party developers to use Douban API, Douban once held a special activity to explain how to use Douban API through oauth: http://www.douban.com/online/10012959/

The source code of this activity can be found on Google Code: Success

As a command lineProgramThe test is successful, but the problem occurs after it is transplanted to Windows Phone.

The key to the problem lies in the differences between the network APIs of Silverlight and C #, and fewer Silverlight APIs. As a result, some network accesses of the above libraries need to be rewritten by themselves.

After carefully reading the httpwebrequest documentation, we found that a network request requires at least three functions, because two asynchronous requests (begingetrequeststream, begingetresponse) are required)

Because almost every action of our Douban app requires requests from the Douban server. If every request requires three functions and the authentication information needs to be added, this is too troublesome,CodeWill become smelly and long

At this time, dry (don't repeat yourself) is particularly important.

As a PM, I decided to encapsulate network access and provide you with a unified and easy-to-use excuse.

I was going to encapsulate the two asynchronous requests by myself. Later I found that a ready-made library is available and very powerful.

This library is restsharp: http://restsharp.org/

In addition, restsharp also provides the corresponding DLL for Windows Phone, which is very convenient. The original three functions now only need a few lines of one function.

For many requests, Douban requires authentication before access. According to Douban's documentation, "When performing post, put, or delete requests, currently, Douban does not support passing the oauth parameter in URL or post form. Therefore, you can only choose to pass the oauth parameter in the header. It seems that we can only add oauth to the HTTP header.

I have encapsulated the following parts:
Namespace addoauthheader {
Public class oauthheader {
String apikey = "Your API key ";
String apikeysecret = "Your API key secret ";
String accesstoken;
String accesstokensecret;
String URI;
String method;
Oauthbase oauth = new oauthbase ();
Isolatedstoragesettings settings = isolatedstoragesettings. applicationsettings;

Public oauthheader (string Uri, string method ){
This. uri = URI;
This. method = method;
}

Public String getheader (){
String nonce = oauth. generatenonce ();
String timestamp = oauth. generatetimestamp ();
String normalizeurl, normalizedrequestparameters;

// Accesstoken = settings ["accesstoken"]. tostring ();
// Accesstokensecret = settings ["accesstokensecret"]. tostring ();

Accesstoken = "ee7ead643e6ea1cb7c082cbb4be4e3 ";
Accesstokensecret = "545138430a2dcc9b ";

String Sig = oauth. generatesignature (
New uri (URI ),
Apikey,
Apikeysecret,
Accesstoken,
Accesstokensecret,
Method,
Timestamp,
Nonce,
Oauthbase. signaturetypes. hmacsha1,
Out normalizeurl,
Out normalizedrequestparameters );
Sig = httputility. urlencode (SIG );

Stringbuilder oauthheader = new stringbuilder ();
Oauthheader. appendformat ("oauth realm = \" \ ", oauth_consumer_key = {0},", apikey );
Oauthheader. appendformat ("oauth_nonce = {0},", Nonce );
Oauthheader. appendformat ("oauth_timestamp = {0},", timestamp );
Oauthheader. appendformat ("oauth_signature_method = {0},", "HMAC-SHA1 ");
Oauthheader. appendformat ("oauth_version = {0},", "1.0 ");
Oauthheader. appendformat ("oauth_signature = {0},", sig );
Oauthheader. appendformat ("oauth_token = {0}", accesstoken );

Return oauthheader. tostring ();
}
}
}

Input a URL and a method (post or put or delete or get), and I will return an oauth header to him. Other students can directly call my code and do not need to worry about authentication issues.

Then how can we make a network request?

I wrote two examples: one is post and the other is get.

Upload data to Douban, post: (I wrote all the instructions to the annotations)

// "Post" instance, taking sending a status as an Example
Private void button#click (Object sender, routedeventargs E)
{
// First, you must instantiate an oauthheader. The input parameters are URL and network request methods (post or get or delete or put or something else)
Oauthheader header = new oauthheader ("http://api.douban.com/miniblog/saying", "Post ");

// For post, to transmit some data to the server, the Douban API uses XML to transmit data, you must first build an XML string
Stringbuilder requestbody = new stringbuilder ("<? XML version = '1. 0' encoding = 'utf-8'?> ");
Requestbody. append ("<entry xmlns: ns0 = \" http://www.w3.org/2005/atom\ "xmlns: DB = \" http://www.douban.com/xmlns/\ "> ");
Requestbody. append ("<content> Hello World </content> ");
Requestbody. append ("</entry> ");

// The following two lines are required for each network request, that is, to establish a connection with api.douban.com
VaR client = new restclient ();
Client. baseurl = "http://api.douban.com ";

// The following line indicates that a request is generated. The first parameter is the path name (not a complete URL), followed by method. Post or method. Get or method. Put or method. Delete.
VaR request = new restrequest ("/miniblog/saying", method. post );

// Set some HTTP headers below

// Set the request format to XML first
Request. requestformat = dataformat. xml;
Request. addheader ("Content-Type", "application/atom + XML ");

// Then write the generated authorization into the HTTP Header
Request. addheader ("Authorization", header. getheader ());

// Write the data to be uploaded to the HTTP request. Add parametertype. requestbody.
Request. addparameter ("application/atom + XML", requestbody. tostring (), parametertype. requestbody );

// Finally, an Asynchronous Network request is made, and the returned response information is parsed and displayed on the page.
Client. executeasync (request, (response) =>
{
VaR resource = response. content;
Debug. writeline (Resource );
});
}

 

// Get instance. Taking obtaining the friend list as an example, get is relatively simple and data is not required.
Private void button3_click (Object sender, routedeventargs E)
{
// Same as above
Oauthheader header = new oauthheader ("http://api.douban.com/people/34788764/contacts? Start-Index = 1 & Max-Results = 50 "," get ");

VaR client = new restclient ();
Client. baseurl = "http://api.douban.com ";

// Note: Do not set? When the parameter is added, the parameter must be implemented at the request. addparameter.
VaR request = new restrequest ("/people/34788764/contacts", method. Get );

// Add the Authentication Header
Request. addheader ("Authorization", header. getheader ());

// Add Parameters
Request. addparameter ("START-index", "1 ");
Request. addparameter ("Max-Results", "50 ");

Client. executeasync (request, (response) =>
{
VaR resource = response. content;
Debug. writeline (Resource );
Textblock1.text = resource;
});
}

This greatly simplifies network requests and truly achieves don't repeat yourself

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.