Skip to content

Instantly share code, notes, and snippets.

@nkint
Last active August 29, 2015 14:23
Show Gist options
  • Save nkint/b5fc9dfb852852e9ce18 to your computer and use it in GitHub Desktop.
Save nkint/b5fc9dfb852852e9ce18 to your computer and use it in GitHub Desktop.
oauth2 token refresher
/*
# random client_id and random client_secret
curl --form client_id='3MVG9Nc1qcT7BbZ1AmkC7gLt_RtFNrY9XCsATBeio3ijPozoP.4qTcKKDGOT5V2V78I.4Ne1RXRTEJjqoZzNC' \
--form client_secret='6092197970455970980' \
--form grant_type=password \
--form username='[email protected]'\
--form password='password' \
https://site.com/services/oauth2/token
# save results to test.json
curl https://cs24.salesforce.com/services/apexrest/Fidelity \
-H 'Authorization: Bearer 00D19000000EFgv!AQ4AQASefbMqsyupDpqCmktdDF5M1x_b2Sf4aQHznBcCP85d2D5c_0kxAifuQQppw4ozgleScpH2pCFqr7P.t4QCmblIEsSi' \
-H "Content-Type: application/json" -d "@test.json"
Note. It requires a plain text files with the following lines:
edpoint url
client_id
client secred
grant type
username
password
Originally implemented for Salesforce.com inside Talend ESB.
*/
package routines;
package routines;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class OAuthRefresher {
private final static String USER_AGENT = "Mozilla/5.0";
static String url = "";
static String client_id = "";
static String client_secret = "";
static String grant_type = "";
static String username="";
static String password="";
public static String instance_url="";
public static String token="";
public static String[] refresh(String filename) throws Exception {
// reset old variables
token = "";
instance_url = "";
readConf(filename);
HttpsURLConnection con = getConnection();
doCall(con);
String response = handleResponse(con);
dirtyParseJSON(response);
String ret[] = {token , instance_url};
return ret;
}
private static void readConf(String filename) {
BufferedReader br = null;
String line = "";
try {
List<String> fields = new ArrayList<String>();
br = new BufferedReader(new FileReader(filename));
while ((line = br.readLine()) != null) {
fields.add(line);
}
url = fields.get(0);
client_id = fields.get(1);
client_secret = fields.get(2);
grant_type = fields.get(3);
username = fields.get(4);
password = fields.get(5);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static boolean dirtyParseJSON(String response) {
// super dirty manual plain json parsing
Map<String, String> responseMap = new HashMap<String,String>();
response = response.substring(1, response.length()-2);
String[] pairs = response.split("\",\"");
for(String pair : pairs) {
String[] s = pair.split("\":\"");
responseMap.put(s[0], s[1]);
}
if(responseMap.containsKey("instance_url") && responseMap.containsKey("access_token")) {
instance_url = responseMap.get("instance_url");
token = responseMap.get("access_token");
return true;
} else {
return false;
}
}
private static String handleResponse(HttpsURLConnection con)
throws IOException {
String responseString = null;
int responseCode = con.getResponseCode();
InputStreamReader inputStream;
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
if (responseCode != 200) {
System.out.println("Error code: "+responseCode);
inputStream = new InputStreamReader(con.getErrorStream());
responseString = "";
} else {
inputStream = new InputStreamReader(con.getInputStream());
}
BufferedReader in = new BufferedReader(inputStream);
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
if(responseString==null) {
responseString = response.toString();
} else {
System.out.println("Error string: "+responseString);
}
return responseString;
}
private static void doCall(HttpsURLConnection con) throws IOException {
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes("client_id="+ client_id+'&');
wr.writeBytes("client_secret="+ client_secret+'&');
wr.writeBytes("grant_type="+ grant_type+'&');
wr.writeBytes("username="+ username+'&');
wr.writeBytes("password="+ password+'&');
wr.flush();
wr.close();
}
private static HttpsURLConnection getConnection()
throws MalformedURLException, IOException, ProtocolException {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("charset", "UTF-8");
con.setRequestProperty("User-Agent", USER_AGENT);
return con;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment