title: OAuth 2 and JavaScript - How to get authorization code
body: <p>Let me first apologize for the length and somewhat rant-ish style of this post.  But as far as I can determine, Box offers no other venue for developer questions/concerns than this site.</p>
  
  <p>The page <a href="http://developers.box.com/docs/" rel="nofollow">http://developers.box.com/docs/</a> under "Authorize" has the example:</p>
  
  <blockquote>
    <p>Example URL</p>
    
    <p><a href="https://www.box.com/api/oauth2/authorize?response_type=code&amp;client_id=YOUR_CLIENT_ID&amp;redirect_uri=YOUR_REDIRECT_URI" rel="nofollow">https://www.box.com/api/oauth2/authorize?response_type=code&amp;client_id=YOUR_CLIENT_ID&amp;redirect_uri=YOUR_REDIRECT_URI</a></p>
    
    <p>Example Callback</p>
    
    <p>YOUR_REDIRECT_URI?code=THE_AUTHORIZATION_CODE</p>
  </blockquote>
  
  <p>If I use XMLHttpRequest (see code below*) with the example URL, I get a response that contains the HTML of the "This app requires that you log in to your Box account" page.  I save the HTML document and open it in the browser.  When the user supplies the password and clicks "Log in" the "This app is requesting permissions to access your Box account" page appears.  When the "Allow" button is clicked, the page is re-directed to the "YOUR_REDIRECT_URI" in the example above.</p>
  
  <p>Ok ... now what?  How does my app (a Firefox extension) access the "YOUR_REDIRECT_URI?code=THE_AUTHORIZATION_CODE" string?  It's just sitting in the location bar of my browser.  Even if my redirect_url is a valid url that executes some php or cgi script that extracts the authorization code from the url, how is my extension code supposed to retrieve it?  The extension is all client-side JavaScript.  Why do I need to bother with re-direct urls at all?  The user supplies their box username/password to my extension during setup.  OAuth 2 provides a "password" grant type which can be used to exchange a username and password for an access token directly.  Can't box support a token request like:</p>
  
  <pre><code>POST https://www.box.com/api/oauth2/token
     grant_type=password&amp;
     username=USERNAME&amp;
     password=PASSWORD&amp;
     client_id=CLIENT_ID
  </code></pre>
  
  <p>This would eliminate the need to authorize the user completely.  The fact that the user has already supplied his username/password to my extension implies authorization.  Making the redirect_url mandatory puts undue obligations to small-time developers like myself.  Do I have to maintain and pay for a secure domain to handle the thousands (or even hundreds of thousands) of XMLHttpRequests per day?  My Firefox extensions are Open Source and free to anyone.  I do not have the resources to pay for that kind of overhead.  I offer box support in my extensions as a convenience to my users.  Box offers no incentive to do this (there is no longer even an affiliate program that rewards developers sending customers their way).</p>
  
  <p>Also, it appears that box does not (yet) support tags in the new API.  My extension relies heavily on this ability.  I've read elsewhere in this forum that tag support is being considered, but I've seen nothing concrete that confirms this will happen (and in a timely manner that will allow us to implement and test it).  This is a deal-breaker for me.</p>
  
  <ul>
  <li><p>JavaScript code snippet that handles the authorization request (contains Firefox dependencies):</p>
  
  <pre><code>var Cc = Components.classes;
  var Ci = Components.interfaces;
  var Cu = Components.utils;
  Cu.import("resource://gre/modules/NetUtil.jsm");
  Cu.import("resource://gre/modules/FileUtils.jsm");
  
  var username = "my_username";
  var password = encodeURIComponent("my_password");
  var client_id = encodeURIComponent("my_clientId");
  var state = encodeURIComponent("authenticated");
  var redirect_uri = encodeURIComponent("https://somebogusurl.com");
  var apiURL = encodeURIComponent("https:www.box.com/api/oauth2/authorize?");
  var response_type = "code";
  var resultsFile = "C:\\Users\\CBaker\\Desktop\\Extension Development\\FEBE\\FEBE 8.0\\work\\results.html"
  var results, doc, tab;
  
  function go(){  
      var req = new XMLHttpRequest(); 
      req.open('POST', 'https://www.box.com/api/oauth2/authorize?response_type=code&amp;client_id='+client_id+'&amp;state='+state+'&amp;redirect_uri='+redirect_uri, true); 
      req.onreadystatechange = function (aEvt) {
          if (req.readyState != 4 || req.status != 200) {
              alert("resStatus: "+resStatus);     
              return false;
          }
          results = req.responseText;
          writeFile(resultsFile,results);
          openFile(resultsFile);
      };
      req.send(null);
      return true;
  }
  
  function writeFile(filename,data){
      var file = new FileUtils.File(filename);
      var ostream = FileUtils.openSafeFileOutputStream(file)
      var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
                                      createInstance(Ci.nsIScriptableUnicodeConverter);
      converter.charset = "UTF-8";
      var istream = converter.convertToInputStream(data);
  
      NetUtil.asyncCopy(istream, ostream, function(status) {
          if (!Components.isSuccessCode(status)) {
              // Handle error!
              return;
          }
  
      });
  }
  
  function openFile(filename){
      var wm = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
      var win = wm.getMostRecentWindow("navigator:browser");
      win.openNewTabWith(resultsFile, this.docURL, null, null);
      return
  }
  go()
  </code></pre></li>
  </ul>