Windows Phone 7, Hammock, OAuth and Sina Weibo’s API

Windows Phone 7, Hammock, OAuth and Sina Weibo’s API

Link:http://www.binzywu.com/2011/02/windows-phone-7-hammock-oauth-and-sina-weibos-api/

OK, I am developing a windows phone 7 app for Sina Weibo. I just simply don’t like the basic authorisation… And OAuth is much better since once you get the access token, you can use it all the time rather than always passing the username and password around. though there are already two Sina Weibo client apps (1 free and 1 is asking for $0.99) in marketplace, my friend Remy and I still want to develop a new app which will be free and open source.

 

We restarted (or I can say started…) the development work from this Monday and things are in good progress. In the meantime, I would like to share what we’ve experienced during development and I hope this can help you if you are thinking to develop your own client on Windows Phone 7 or Silverlight for Sina Weibo. So this first entry is about getting OAuth access token for Sina Weibo via Hammock. Hammock is a great lib for you to consume and wrap RESTful services and it supports OAuth and XAuth.

Step 1 register your app.
Sure, you need to apply/register an application onhttp://open.t.sina.com.cn/. You will then get your app key and secret (which is actually consumer key and secret).

Step 2 authentication.
OAuth is quite simple and straightforward. In summary, you need to pass your consumer key and secret to get the request token, like this,

void OAuthTest()
{
    RestClient c = new RestClient()
    {
        Authority = "http://api.t.sina.com.cn/",
        HasElevatedPermissions = true,
        Credentials = new OAuthCredentials()
        {
            ConsumerKey = "your appkey",
            ConsumerSecret = "your appsecret",
            SignatureMethod = OAuthSignatureMethod.HmacSha1,
            ParameterHandling = 
OAuthParameterHandling.HttpAuthorizationHeader,
            Version = "1.0"
        }
    };

    RestRequest r = new RestRequest()
    {
        Path = "oauth/request_token",

    };

    c.BeginRequest(r, new RestCallback(Callback));

}

void Callback(RestRequest request, RestResponse response, 
object userState)
{
    Regex r = 
new Regex("oauth_token=([^&.]*)&oauth_token_secret=([^&.]*)");
    var match = r.Match(response.Content);
    token = match.Groups[1].Value;
    tokensecret = match.Groups[2].Value;
}


once you get the request token and tokensecret, you can pass them along with consumer key for the authorization. Then Sina Weibo API will ask for username and password. But for client app like this, you may want user provide the info at your app and you take care the whole interaction in app. So you could generate a dynamic callback page. Beyond, the Sina Weibo API supports directly xml callback to return the xml which contains the oauth_verifier.

RestClient c = new RestClient()
{
    Authority = "http://api.t.sina.com.cn/",
};

RestRequest req = new RestRequest()
{
    Path = string.Format("oauth/authorize?{0}&oauth_callback=xml
&userId={1}&passwd={2}", response.Content, "user", "password")
};

c.BeginRequest(req, new RestCallback(Callback2));        

void Callback2(RestRequest request, RestResponse response,
 object userState)
{
    Regex r = new Regex("<oauth_token>(.*?)</oauth_token>
<oauth_verifier>(.*?)</oauth_verifier>");
    var match = r.Match(response.Content);
}


then you are ready to ask for the access token,

RestClient c = new RestClient()
{
    Authority = "http://api.t.sina.com.cn/",
    HasElevatedPermissions = true,
    Credentials = new OAuthCredentials()
    {
        ConsumerKey = "your appkey",
        ConsumerSecret = "your appsecret",
        Token = "request token",
        TokenSecret = "request tokensecret",
        Verifier = "your oauth verifier from last step",
        SignatureMethod = OAuthSignatureMethod.HmacSha1,
        ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
        Type = OAuthType.AccessToken,
        Version = "1.0"
    }
};

RestRequest r2 = new RestRequest()
{
    Path = "oauth/access_token",

};

c.BeginRequest(r2, new RestCallback(Callback3));

public void Callback3(RestRequest request, RestResponse response, 
object userState)
{
    // you will get format like this and that's your access
 token: oauth_token=token&oauth_token_secret=secret&user_id=id
    var s = response.Content;
}


Step 3 make an update to your statuses!
As mentioned before once you’ve got the access token, the token can be used until the user revokes the authentication. The following things will be very simple. like if you want to post an update from your app, you just need some very familiar codes.

        private void Test()
        {
            RestClient c = new RestClient()
            {
                Authority = "http://api.t.sina.com.cn/",
                HasElevatedPermissions = true,
                Credentials = new OAuthCredentials()
                {
                    ConsumerKey = "your appkey",
                    ConsumerSecret = "your appsecret",
                    Token = "your access token",
                    TokenSecret = "your access tokensecret",
                    SignatureMethod = OAuthSignatureMethod.HmacSha1,
                    ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                    Type = OAuthType.ProtectedResource,
                    Version = "1.0"
                }
            };

            RestRequest r2 = new RestRequest()
            {
                Path = "statuses/update.xml"
            };

            r2.AddParameter("status", "hello world");
            r2.Method = WebMethod.Post;
            c.BeginRequest(r2, new RestCallback(Callback));

        }

        void Callback(RestRequest request, RestResponse response,
 object userState)
        {
            // check wheather post is successful
        }


Enjoy.

 

references:
OAuth: http://oauth.net
Sina Weibo API: http://open.t.sina.com.cn/
Hammock: http://hammock.codeplex.com

 

18. February 2011 by binzywu
Categories: MobileProgramming | Tags: .NetAPIc#csharpHammockOAuth,SinaWeibowindows phone 7wp7客户端微博新浪Leave a comment

posted @ 2012-11-26 16:57  ppshinebl  阅读(272)  评论(0编辑  收藏  举报