Pages

Wednesday, February 26, 2014

Box.com Oauth2 Test Client

Getting the Access Token from the Box.COM as follows

1. Get the Authorization code from the Box.COM

2. Get the Access Token Based on the Authorization Code granted by Box.COM


Pre-Requisite


1. Http Client 4.1 jar files in the Class Path.
2. Generate the Client_ID and Client_Secret in the Box.COM .

1. Get the Authorization code from the Box.COM

Get the Authorization code from the Box.COM as three step process.

Stept 1. Send the Post Request to the Box.com with client id, redirect_uri, and response_type.

In the Sample code, invoking the sendPostRequestAuthorization() method to initial the post Authentication request process.

Stept 2. Authenticate the user against Box.com with Admin Credentials

In the Sample Code, Invoking the sendPostAuthorize() method to authenticate the user against the Box.COM

Step 3. Grant Access to the User to access the Box.com and it generate the Authorization Code.

In the Sample Code, Invoking the sendPostAuthorize() method to grant to access to box.com and  generate the Authorization Code


2. Get the Access Token Based on the Authorization Code granted by Box.COM


The following parameters are required in the request to get the access token using the REST API. They are

grant_type=authorization_code
code=clientCode
client_id=<Client ID>
client_secret=CLIENT_SECRET

 REST URL: https://www.box.com/api/oauth2/token
 Request Type: Post

In the Sample Code, Invoke the getAccessToken() method and it will get the access token from the box.com



Sample Code:



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;


public class OauthClientBox
{

    private static String BOX_AUTHORIZE_URL="https://app.box.com/api/oauth2/authorize";
    private static String BOX_OAUTH_TOKEN_URL="https://www.box.com/api/oauth2/token";
    private static String CLIENT_ID="<Replace With Your Client ID>";
    private static String CLIENT_SECRET="<Replace With your Client Secret>";
    private static String USER_NAME="<Co Admin User Name>";
    private static String PASSWORD="Co Admin Password";
    private static String REDIRECT_URL="<Redirect URL>";
   
    /**
     * This is required to carry forward the box.com cookies from each request
     */
    private static BasicCookieStore cookieStore= new BasicCookieStore();
    private static BasicHttpContext context= new BasicHttpContext();

   
   
    public OauthClientBox() {
    }

    public static void main(String args[]) throws Exception
    {
       String accessToken=getAccessToken();
    }
   
public static String getAccessToken()
{
       context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
      
        // Returns the HTML Form Data
        String htmlData=sendPostRequestAuthorization();
        // Separating the Form Data. For Example <form name="login_form" action="http://localhost" method="post"><input type=hidden name=test/><input type=submit value=login></form>
        String formData=getFormRawData(htmlData);
        // Constructing the Form Data as a Key as Html Field element name , and values as a Map such as name=<Html Field name>,type=hidden or submit , value=<html field value>
        Map<String,Map<String, String>> loginFormElements= constructFormData(formData);
        if(loginFormElements != null && !loginFormElements.isEmpty())
        {
            // Setting the User Name and Password for Authentication
            loginFormElements.get("login").put("value", USER_NAME);
            loginFormElements.get("password").put("value", PASSWORD);
        }
        // Getting the Form Action and Method type as a Map. For Example. action="http://localhost" method="post"
        Map<String, String> formDataMap= getFormData(formData);
    //Sending Authentication Request to Box.com   
  String authenticatedHtmlData= sendPostAuthorize(loginFormElements,false,formDataMap.get("action"));
        
 
      formData=getFormRawData(authenticatedHtmlData);

// Constructing the Form Data as a Key as Html Field element name , and values as a Map such as name=<Html Field name>,type=hidden or submit , value=<html field value>
       
        Map<String,Map<String, String>> authFormElements= constructFormData(formData);
      // Getting the Form Action and Method type as a Map. For Example. action="http://localhost" method="post"
        formDataMap= getFormData(authenticatedHtmlData);
//Sending the Authorization Request to Box.Com to authorize and grant the access to the user and it will return the code. 
        String code=sendPostAuthorize(authFormElements,false,formDataMap.get("action"));
        System.out.println("Final Authorize Code :"+code);
        // Getting the Access Token Based on the Authorization code
        String accessToken= getAccessToken(code);
        System.out.println("Final Access Token :"+accessToken);
        return  accessToken;
}
   
    public static String getAccessToken(String clientCode)
    {
        String data=null;
        HttpClient client= new DefaultHttpClient();
        HttpPost post= new HttpPost(BOX_OAUTH_TOKEN_URL);
        List<NameValuePair> nameValueParams= new ArrayList<NameValuePair>();
        nameValueParams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        nameValueParams.add(new BasicNameValuePair("code", clientCode));
        nameValueParams.add(new BasicNameValuePair("client_id", CLIENT_ID));
        nameValueParams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
          
        try
        {
            post.setEntity(new UrlEncodedFormEntity(nameValueParams));
            HttpResponse response=client.execute(post);
            System.out.println(String.format("status code  %d",  response.getStatusLine().getStatusCode()));
            if(response.getStatusLine().getStatusCode() == 200)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null)
                {
                    System.out.println("Response content length: " + entity.getContentLength());
                    BasicResponseHandler handler= new BasicResponseHandler();
                    data=handler.handleResponse(response);
                    EntityUtils.consume(entity);
                }
            }
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return data;
    }
   
    private static String getFormRawData(String htmlData)
    {
        String result="";
        int startIndex = htmlData.indexOf("<form");
        int endIndex = htmlData.indexOf("</form>");
        if(startIndex !=-1 && endIndex !=-1)
        {
            result = htmlData.substring(startIndex,endIndex+7);  
        }
        return result;
    }

   
   
   
    // Sending Box API Initial Authorization Request
    private static String sendPostRequestAuthorization()
    {
        String result=null;
        DefaultHttpClient client= new DefaultHttpClient();
        try
        {
          
            HttpPost post= new HttpPost(BOX_AUTHORIZE_URL);
            List<NameValuePair> params= new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("response_type", "code"));
            params.add(new BasicNameValuePair("client_id", CLIENT_ID));
            params.add(new BasicNameValuePair("redirect_uri", REDIRECT_URL));
            post.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse response=client.execute(post,context);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            if(statusCode==200)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null)
                {
                    BasicResponseHandler handler= new BasicResponseHandler();
                    result=handler.handleResponse(response);
                    EntityUtils.consume(entity);
                }
            }
          
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }

    private static String sendPostAuthorize(Map<String, Map<String, String>> data,boolean authrize,String url)
    {
        String result=null;
        DefaultHttpClient client= new DefaultHttpClient();
        try
        {
          
            HttpPost post= new HttpPost(url);
            Set<String> inputKey= data.keySet();
            List<NameValuePair> params= new ArrayList<NameValuePair>();
            for (String string : inputKey) {
                Map<String, String> inputData= data.get(string);
                String type=inputData.get("type");
                if(type != null && !type.equalsIgnoreCase("submit"))
                {
                    params.add(new BasicNameValuePair(string, inputData.get("value")));
                }
            }
            if(authrize)
            {
                params.add(new BasicNameValuePair("consent_accept", "Grant access to Box"));
            }
            post.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse response=client.execute(post,context);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            if(statusCode==200)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null)
                {
                    BasicResponseHandler handler= new BasicResponseHandler();
                    result=handler.handleResponse(response);
                    EntityUtils.consume(entity);
                }
            }
            else if(statusCode==302)
            {
                String redirectURL = response.getFirstHeader("Location").getValue();
                String codeStr="code=";
                int index=redirectURL.indexOf("code=");
                if(index !=-1)
                {
                    String code=redirectURL.substring(index+codeStr.length());
                    result=code;
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }

    private static Map<String,Map<String, String>> constructFormData(String data)
    {
        Map<String,Map<String, String>> inputElements= new HashMap<String,Map<String, String>>();
        int startIndex= data.indexOf("<input");
        int endIndex= data.indexOf(">",startIndex);
        while(startIndex != -1 && endIndex !=-1)
        {
            String inputElement= data.substring(startIndex, endIndex+1);
            Map<String, String> inputData= getInputElement(inputElement);
            inputElements.put(inputData.get("name"), inputData);
            startIndex=data.indexOf("<input", endIndex+1);
            endIndex= data.indexOf(">",startIndex);
        }
        return inputElements;
    }
   
    private static Map<String, String> getInputElement(String element)
    {
        Map<String, String> row= new HashMap<String, String>();
      
        int nameIndex=element.indexOf("name=");
        int typeIndex=element.indexOf("type=");
        int valueIndex=element.indexOf("value=");
      
        if(nameIndex != -1)
        {
            String data= element.substring("name=".length()+nameIndex);
            row.put("name", getValue(data));
        }
        if(typeIndex != -1)
        {
            String data= element.substring("type=".length()+typeIndex);
            row.put("type", getValue(data));
        }
        if(valueIndex != -1)
        {
            String data= element.substring("value=".length()+valueIndex);
            row.put("value", getValue(data));
        }
      
        return row;
    }
   
    private static String getValue(String data)
    {
        String result="";
        int startQuote=data.indexOf("\"");
        int endQuote=data.indexOf("\"",startQuote+1);
        if(startQuote != -1 && endQuote !=-1)
        {
            result=data.substring(startQuote+1,endQuote);
        }
        return result;  
    }

    public static Map<String, String> getFormData(String formData)
    {
        Map<String, String> formDataMap= new HashMap<String,String>();
        int startIndex= formData.indexOf("<form");
        int endIndex= formData.indexOf(">",startIndex);
        if(startIndex !=-1 && endIndex !=-1)
        {
            String form= formData.substring(startIndex,endIndex+1);
            String action=getValue(form,"action=");
            String method=getValue(form,"method=");
            formDataMap.put("action", action);
            formDataMap.put("method", method);
        }
        return formDataMap;
    }
    private static String getValue(String element,String query)
    {
        String result="";
        int nameIndex=element.indexOf(query);
        if(nameIndex != -1)
        {
            String data= element.substring(query.length()+nameIndex);
          
            int startQuote=data.indexOf("\"");
            int endQuote=data.indexOf("\"",startQuote+1);
            if(startQuote != -1 && endQuote !=-1)
            {
                result=data.substring(startQuote+1,endQuote);
            }
        }
        return result;
    }




   
   
}