Monday, November 25, 2013

OAuth authentication to Box.com via node.js

Below is some code that implements a 'hello world'-level integration between a node.js app and the box.com 2.0 API.

Box uses OAuth 2.0 for app access to user folders/files.  The majority of the code below is just to get thru the OAuth 2.0 handshakes.  That handshake process mandates the first step be via GUI - hence the simplistic auth.html page below.  The user passes their username/password directly to box.com, bypassing your app.  Box has a fairly detailed discussion of their OAuth process here.


First step in the OAuth process is to pass the client_id and redirect_uri of your box.com app to box.com. You obtain a client_id and client_secret when you register your app at Box.com.  Below is a bare-bones GUI for sending that info to Box.

auth.html - Code

auth.html - Rendered in the Browser




The user would push the 'submit' button to start the process.  Box will verify this is a valid client_id and then redirect to their login page.



Following a successful account login, Box will present the user with the choice as to whether to allow your app to access their files.



 When the user pushes the 'Grant' button, the following chain of events are set in motion.
  1. Box initiates a HTTPS GET/POST to the redirect URI you specified in the initial GET/POST to Box.
  2. That POST will contain a OAuth 'code' parameter.  You will use that in the next step.
  3. That temporary (30 second lifetime) 'code' parameter needs to be swapped for an OAuth 'token'.  The swap happens with a HTTPS POST back to Box.  That POST needs to contain several authentication parameters: client_id (again), client_secret, and your newly-obtained 'code'.
  4. If the POST to Box is successful, they will return back a JSON-formatted list of items, one of which is an OAuth token.
  5. At this point, you can invoke the Box.com's REST API (API 2.0) by including that token in 'Authorization' header in your GET's.
Node.js code below to implement all the above.

boxserver.js





Here are screenshots of a box.com folder and the results of the simple code above being run against it.


























































No comments:

Post a Comment