all posts

Accessing the Miso API: a sample ASP.NET application

Published to Blog on 9 Jan 2011

Miso recently launched the initial phase of their API and make use of OAuth (similar to Twitter’s implementation) to allow user’s to authenticate with Miso and authorize your application to act on their behalf. The documentation is well written and easy to follow if you have experience working with APIs and OAuth. The sample application is written in Ruby and a fellow enthusiast contributed a version in PHP. This post provides sample code for authenticating a user to Miso and authorizing your application using an ASP.NET application (C#).

The first thing you have to do is register your application. This will provide your Consumer Key and Consumer Secret, which are used by your application to sign your requests so that Miso knows that you are who you say your are.

After you’ve registered your application you now have to build your app that does something interesting with the Miso API. Following are the steps needed to get OAuth access to the Miso API when a user accesses your application (explained in Miso’s documentation):

1. Fetch a request token by making a GET request to https://gomiso.com/oauth/request_token/. The request should include a callback url for an address that the user will be sent back to once they authorize your application. The response will contain a value for oauth_token, save this as it will be used in the next step.

2. Redirect the user to the authorization URL. The request token you retrieved in the previous step will be sent as a parameter of the request. After authenticating your application the user is sent back to the address of the callback url that you specified in step 1.

3. The request to your callback url will contain two pieces of data appended to the querystring that you need to grab: oauth_token and oauth_verifier.

4. Now you fetch the access token by making a GET request to https://gomiso.com/oauth/access_token and passing in the token and verifier you got in the previous step. The response will contain a value for oauth_token and oauth_token_secret. Save these, they are your Access Token and Access Token Secret.

5. Now you have everything you need to sign your requests to Miso and act on behalf of your user. All requests made to the Miso API should now include those four pieces of information.

 

Managing Miso’s OAuth Handshake with .NET

The list above is a general description of what is required, but you came here looking for something a little more concrete didn’t you? The first thing you’ll need is an OAuth library. I chose to use Twitterizer’s OAuth implementation. Get the source code and compile and then grab the Twitterizer.OAuth dll and reference it in your application (or drop it in your bin folder or whatever meets your needs). Make sure you follow the licensing requirements – basically make sure you give Twitterizer credit for the code. In the code examples below, two of the classes used are from Twitterizer.OAuth: OAuthTokens and WebRequestBuilder.

For performing the OAuth handshake you’ll basically need two pages, one to start the process and a page for the callback (technically you only really need the callback page depending on how you choose to kick-off the process). I created a couple of additional classes, OAuthConfiguration and OAuthUtility, to combine much of the code that was repeated and keep the logic terse, readable, and understandable. The code for both of those classes is provided further down the page. First I created a “default.aspx” page and added the following code to perform steps 1 and 2 above:

OAuthConfiguration config = new OAuthConfiguration();
 
//Perform a token request
string result = OAuthUtility.ConsumerRequest(
       "GET", 
       "https://gomiso.com/oauth/request_token/&oauth_callback=" + 
            HttpUtility.UrlEncode("http://yourwebsite.com/callback.aspx"),
       config);
 
NameValueCollection nvc = HttpUtility.ParseQueryString(result);
string requestToken = nvc["oauth_token"];  
 
//Send the user to the Miso Authorization page
Response.Redirect(string.Format("https:/gomiso.com/oauth/authorize?oauth_token={0}", requestToken));

 

Next I created callback.aspx to serve as the callback that the user is sent to by Miso after authorizing your application. It performs steps 3 and 4 above.

OAuthConfiguration config = new OAuthConfiguration();
 
//Pull the token and verifier from the request (querystring) received after user authenticated 
//and authorized
string oauthToken = Request["oauth_token"];
string oauthVerifier = Request["oauth_verifier"];
 
//You should add code to handle auth token or verifier not being sent
 
//Now send request using the token and verifier to get the access token and access token secret
string result = OAuthUtility.ConsumerRequest(
     "GET", 
     string.format(
          "https://gomiso.com/oauth/access_token/?oauth_token={0}&oauth_verifier={1}", 
          oauthToken, 
          oauthVerifier) 
     config);            
 
NameValueCollection nvc = HttpUtility.ParseQueryString(result);
string accessToken = nvc["oauth_token"];
string accessTokenSecret = nvc["oauth_token_secret"];
 
// We now have everything we need to create a token to be used for any future requests to 
// Miso API on behalf of the user
OAuthTokens token = OAuthUtility.BuildToken(config.ConsumerKey, config.ConsumerSecret, 
                                            accessToken, accessTokenSecret);
// now store token for this user (db, session, etc)
// now redirect the user to some other page where they can do something interesting

 

Making Requests to the Miso API

Once you have the completed token, making requests to the Miso API for the user is as simple as something like this:

string response = OAuthUtility.Request(
              "GET", 
              "http://gomiso.com/api/oauth/v1/checkins.json?user_id=UserIdGoesHere&count=5",
              token);

 

OAuthConfiguration Class

Neither this nor the utility class are necessary, you could have all this code inline with the logic, but I found them useful. For the sake of an example application I set the values of my consumer key and consumer secret directly in the code, but in a real-life app you might want to grab these from a configuration file, database, etc. This class could also contain the values for the various Miso urls and parameter names so they are not scattered about the rest of the code.

public class OAuthConfiguration
{
    string CONSUMER_KEY = "Your Consumer Key";
    string CONSUMER_SECRET = "Your Consumer Secret";
 
    public string ConsumerKey
    {
        get { return CONSUMER_KEY; }
    }
    public string ConsumerSecret
    {
        get { return CONSUMER_SECRET; }
    }
}

 

OAuthUtility Class

This class basically handles creating a token used to sign requests and making the signed HTTP requests and returning values. You’ll notice that the ConsumerRequest method only set values on the token for ConsumerKey and ConsumerSecret and do not set values for AccessToken and AccessTokenSecret. That is because that method is used to make the initial token request and to request the access token (step 1 and step 4 above) before we have the access token, so the only thing you need to sign the request with is your consumer information.

public class OAuthUtility {
 
    public static OAuthTokens BuildToken(string consumerKey, string consumerSecret, 
                                         string accessToken, string accessTokenSecret) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.ConsumerKey = consumerKey;
        tokens.ConsumerSecret = consumerSecret;
        if (!string.IsNullOrEmpty(accessToken) && !string.IsNullOrEmpty(accessTokenSecret)) {
            tokens.AccessToken = accessToken;
            tokens.AccessTokenSecret = accessTokenSecret;
        }
        return tokens;
    }
 
    public static string ConsumerRequest(string methodType, 
                                         string url, 
                                         OAuthConfiguration config) {
        OAuthTokens token = BuildToken(config.ConsumerKey, config.ConsumerSecret, null, null);
        return Request(methodType, url, token);
    }
 
    public static string Request(string methodType, 
                                 string url, 
                                 OAuthTokens token) {
        WebRequestBuilder requestBuilder = new WebRequestBuilder(
                                  new Uri(url), 
                                  methodType == "POST" ? HTTPVerb.POST : HTTPVerb.GET, 
                                  token);
        string result = "";
        HttpWebRequest webRequest = requestBuilder.PrepareRequest();
        WebResponse webResponse = null;
        try {
            using (webResponse = webRequest.GetResponse()) {
                using (StreamReader streamReader = 
                        new StreamReader(webResponse.GetResponseStream())) {
                    result = streamReader.ReadToEnd();
                    streamReader.Close();
                }
            }
        } catch (WebException) {
            throw;
        } catch (Exception) {
            throw;
        } finally {
            try {
                if (webRequest != null) {
                    webRequest.GetRequestStream().Close();
                }
                if (webResponse != null) {
                    webResponse.GetResponseStream().Close();
                }
            } catch { }
        }
        return result;
    }  
}

 

That should be enough info to get you started working with the Miso API in .NET. Enjoy!

NOTE: You can see a live example of me using the Miso API by going to my home page (danhounshell.com) and clicking the "Television and Movies" link.

 


Dan Hounshell
Web geek, nerd, amateur maker. Likes: apis, node, mobile, motorcycles, watches, food, Nashville, Savannah, Cincinnati and family. Dislikes: mean people
Dan Hounshell on Twitter