Monday, August 12, 2013

Javascript & OAuth API calls

Javascript is convenient to make OAuth API calls. User places a simple button to retrieve an OAuth token by way of an API call. The type of OAuth flow required for this could be based on password since it is convenient to ask the user what the password is. This could appear with rich Ajax soft sliding appearance of a text input for password on the click of the token retrieval button. The password entry can then directly be used to make the API calls. Helper libraries from the site hosting this page such as scripts at the root level or framework can be used to simplify the code. Here is an example:
<!DOCTYPE html>
<html>
<head>
<script>
function parseJSON(data) {
    return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))();
}
function GetAccessToken()
{
if (document.getElementById("password").value == "")
{
alert("Enter your password to retrieve an access token");
return;
}

        var xdr= new XDomainRequest();
        xdr.timeout = 10000;
xdr.onreadystatechange=function()
  {
  if (xdr.readyState==4 && xdr.status==200)
    {
  var resp = parseJSON(xdr.responseText);
  document.getElementById(params[access_token]).innerHTML=resp.access_token;
    }
        }
  xdr.open("POST","https://testhost.openapi.starbucks.com/v1/token/",true);
  xdr.setRequestHeader("Content-type","application/json");
  xdr.send("api_Key="+ document.getElementById("apiKey").value +"&grant_type=password&client_id=" + document.getElementById("apiKey").value + "&username=" + mashery_info.username + "&password=" + document.getElementById("password").value + "&scope=test_scope&client_secret=" + document.getElementById("apiSecret").value);
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="GetAccessToken()">Get Access Token</button>
<input type="password" id="password" name="password"  />
<input type="text" name="params[access_token]" value="" placeholder="required" />
</body>
</html>

No comments:

Post a Comment