Created
February 27, 2014 07:06
-
-
Save howardzhang/9245681 to your computer and use it in GitHub Desktop.
Using Apache HttpClient which acts as browser to get authorization code. Get through OAuth 2.0 of Box.com without browser.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.box.boxjavalibv2.*; | |
import com.box.boxjavalibv2.dao.*; | |
import com.box.boxjavalibv2.exceptions.*; | |
import com.box.boxjavalibv2.requests.requestobjects.*; | |
import com.box.boxjavalibv2.resourcemanagers.*; | |
import com.box.restclientv2.exceptions.*; | |
import java.io.*; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
import java.util.ArrayList; | |
import java.util.*; | |
import java.lang.Exception; | |
import org.apache.http.impl.client.DefaultHttpClient; | |
import org.apache.http.client.methods.HttpPost; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.HttpRequest; | |
import org.apache.http.params.HttpParams; | |
import org.apache.http.client.params.HttpClientParams; | |
import org.apache.http.message.BasicNameValuePair; | |
import org.apache.http.client.entity.UrlEncodedFormEntity; | |
import org.apache.http.params.HttpConnectionParams; | |
import org.apache.commons.httpclient.cookie.CookiePolicy; | |
import org.apache.http.protocol.HTTP; | |
import org.apache.http.util.EntityUtils; | |
import org.apache.http.Header; | |
import org.apache.http.impl.client.DefaultRedirectStrategy; | |
import org.apache.http.protocol.HttpContext; | |
import org.apache.http.ProtocolException; | |
import java.net.CookieHandler; | |
import java.net.CookieManager; | |
import java.net.URL; | |
import java.net.URLEncoder; | |
import javax.net.ssl.HttpsURLConnection; | |
import org.jsoup.Jsoup; | |
import org.jsoup.nodes.Document; | |
import org.jsoup.nodes.Element; | |
import org.jsoup.select.Elements; | |
import java.nio.charset.*; | |
import org.apache.http.NameValuePair; | |
import org.apache.http.client.HttpClient; | |
import org.apache.http.client.methods.HttpGet; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
public class TestAuthorization { | |
public static final int PORT = 4000; | |
public static final String key = "YOUR CLIENT KEY"; | |
public static final String secret = "YOUR CLIENT SECRET"; | |
private final String USER_AGENT = "Mozilla/5.0"; | |
private String cookies; | |
private HttpClient client = new DefaultHttpClient(); | |
public static void main(String[] args) throws AuthFatalFailureException, | |
BoxServerException, BoxRestException, Exception { | |
if (key.startsWith("YOUR")) { | |
System.out | |
.println("Before this sample app will work, you will need to change the"); | |
System.out.println("'key' and 'secret' values in the source code."); | |
return; | |
} | |
String code = ""; | |
String url = "https://app.box.com/api/oauth2/authorize?response_type=code&client_id=" | |
+ key + "&redirect_uri=http%3A//localhost%3A" + PORT; | |
TestAuthorization http = new TestAuthorization(); | |
// make sure cookies is turn on | |
CookieHandler.setDefault(new CookieManager()); | |
String page = http.GetPageContent(url); | |
Map<String,String> loginFormData = new HashMap<String, String>(); | |
loginFormData.put("login", "your_email@box.com"); | |
loginFormData.put("password", "your_password"); | |
List<NameValuePair> postParams = http.getParams(page, "login_form",loginFormData); | |
String grantpage = http.sendPost(url, postParams,false); | |
Map<String,String> grantFormData = new HashMap<String, String>(); | |
grantFormData.put("consent_reject", ""); | |
List<NameValuePair> grantParams = http.getParams(grantpage,"consent_form",grantFormData); | |
code = http.sendPost(url,grantParams,true); | |
System.out.println(code); | |
BoxClient client = getAuthenticatedClient(code); | |
BoxFolder boxFolder= client.getFoldersManager().getFolder("0",null); | |
ArrayList<BoxTypedObject> folderEntries = boxFolder.getItemCollection().getEntries(); | |
int folderSize = folderEntries.size(); | |
for (int i = 0; i <= folderSize-1; i++){ | |
BoxTypedObject folderEntry = folderEntries.get(i); | |
String name = (folderEntry instanceof BoxItem) ? ((BoxItem)folderEntry).getName() : "(unknown)"; | |
System.out.println("i:" + i + ", Type:" + folderEntry.getType() + ", Id:" + folderEntry.getId() + ", Name:" + name); | |
} | |
BoxEventsManager boxEventsManager = client.getEventsManager(); | |
BoxEventCollection eventsCollection = boxEventsManager.getEvents(BoxEventRequestObject.getEventsRequestObject(0)); | |
for (BoxTypedObject item : eventsCollection.getEntries()) { | |
BoxEvent event = (BoxEvent) item; | |
System.out.println("[Events]Id:" + event.getId() + ", Type:" + event.getEventType()); | |
} | |
} | |
private static BoxClient getAuthenticatedClient(String code) throws BoxRestException, BoxServerException, AuthFatalFailureException { | |
BoxClient client = new BoxClient(key, secret); | |
BoxOAuthRequestObject obj = BoxOAuthRequestObject.createOAuthRequestObject(code, key, secret, "http://localhost:" + PORT); | |
BoxOAuthToken bt = client.getOAuthManager().createOAuth(obj); | |
client.authenticate(bt); | |
return client; | |
} | |
private String sendPost(String url, List<NameValuePair> postParams, boolean getAuthCode) throws Exception { | |
HttpPost post = new HttpPost(url); | |
// add header | |
post.setHeader("Host", "app.box.com"); | |
post.setHeader("User-Agent", USER_AGENT); | |
post.setHeader("Accept", | |
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); | |
post.setHeader("Accept-Language", "en-US,en;q=0.5"); | |
post.setHeader("Cookie", getCookies()); | |
post.setHeader("Connection", "keep-alive"); | |
post.setHeader("Referer", | |
"https://app.box.com/api/oauth2/authorize?response_type=code&client_id="+ key + "&redirect_uri=http%3A//localhost%3A" + PORT); | |
post.setHeader("Content-Type", "application/x-www-form-urlencoded"); | |
post.setEntity(new UrlEncodedFormEntity(postParams)); | |
HttpResponse response = client.execute(post); | |
int responseCode = response.getStatusLine().getStatusCode(); | |
//System.out.println("\nSending 'POST' request to URL : " + url); | |
//System.out.println("Post parameters : " + postParams); | |
System.out.println("Response Code : " + responseCode); | |
BufferedReader rd = new BufferedReader(new InputStreamReader(response | |
.getEntity().getContent())); | |
StringBuffer result = new StringBuffer(); | |
String line = ""; | |
while ((line = rd.readLine()) != null) { | |
result.append(line); | |
} | |
setCookies(response.getFirstHeader("Set-Cookie") == null ? "" | |
: response.getFirstHeader("Set-Cookie").toString()); | |
//get response headers | |
String code = ""; | |
Header[] headers = response.getAllHeaders(); | |
for (Header header : headers) { | |
//System.out.println("[Response Header] Name: " + header.getName() + " Value: " + header.getValue()); | |
if (header.getName().equals("Location")){ | |
code = header.getValue().substring(header.getValue().indexOf("code=")+5); | |
} | |
} | |
if (getAuthCode) | |
return code; | |
else | |
return result.toString(); | |
} | |
private String GetPageContent(String url) throws Exception { | |
HttpGet request = new HttpGet(url); | |
request.setHeader("User-Agent", USER_AGENT); | |
request.setHeader("Accept", | |
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); | |
request.setHeader("Accept-Language", "en-US,en;q=0.5"); | |
HttpResponse response = client.execute(request); | |
int responseCode = response.getStatusLine().getStatusCode(); | |
//System.out.println("\nSending 'GET' request to URL : " + url); | |
System.out.println("Response Code : " + responseCode); | |
BufferedReader rd = new BufferedReader(new InputStreamReader(response | |
.getEntity().getContent())); | |
StringBuffer result = new StringBuffer(); | |
String line = ""; | |
while ((line = rd.readLine()) != null) { | |
result.append(line); | |
} | |
// set cookies | |
setCookies(response.getFirstHeader("Set-Cookie") == null ? "" | |
: response.getFirstHeader("Set-Cookie").toString()); | |
return result.toString(); | |
} | |
public List<NameValuePair> getParams(String html, String formname, | |
Map<String,String> formdata) throws UnsupportedEncodingException { | |
System.out.println("Extracting form's data..."); | |
Document doc = Jsoup.parse(html); | |
Element loginform = doc.getElementsByAttributeValue("name", | |
formname).first(); | |
Elements inputElements = loginform.getElementsByTag("input"); | |
List<NameValuePair> paramList = new ArrayList<NameValuePair>(); | |
for (Element inputElement : inputElements) { | |
String ekey = inputElement.attr("name"); | |
String value = inputElement.attr("value"); | |
for (String datakey : formdata.keySet()) { | |
if (ekey.equals(datakey)) | |
value = formdata.get(datakey); | |
} | |
paramList.add(new BasicNameValuePair(ekey, value)); | |
} | |
return paramList; | |
} | |
public String getCookies() { | |
return cookies; | |
} | |
public void setCookies(String cookies) { | |
this.cookies = cookies; | |
} | |
} |
Hello,
This code is working for me when Ping federate is not configured.
I am not sure but this code is not working for me when there is Ping SSO enabled (required only mode) on Box.
Can anyone know how to get this work with Ping SSO required mode ?
-Yogesh
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is this still working for you? I am getting "405/Method Not Allowed" when trying to send the POST request with login params.
-Samir