Skip to content

Instantly share code, notes, and snippets.

@entaq
Created November 13, 2012 17:17
Show Gist options
  • Save entaq/4067085 to your computer and use it in GitHub Desktop.
Save entaq/4067085 to your computer and use it in GitHub Desktop.
Simple SalesForce oAuth Flow
/**
reference -
http://wiki.developerforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com
http://www.salesforce.com/us/developer/docs/api_rest/index.htm
**/
////handle all requests here
function doGet(e) {
var HTMLToOutput;
if(e.parameters.code){//if we get "code" as a parameter in, then this is a callback. we can make this more explicit
getAndStoreAccessToken(e.parameters.code);
HTMLToOutput = '<html><h1>Finished with oAuth</h1></html>';
}
else if(isTokenValid()){//if we already have a valid token, go off and start working with data
HTMLToOutput = '<html><h1>Already have token</h1></html>';
}
else {//we are starting from scratch or resetting
return HtmlService.createHtmlOutput("<html><h1>Lets start with oAuth</h1><a href='"+getURLForAuthorization()+"'>click here to start</a></html>");
}
HTMLToOutput += getData();
return HtmlService.createHtmlOutput(HTMLToOutput);
}
//do meaningful salesforce access here
function getData(){
//var getDataURL = 'http://na9.salesforce.com/services/data/v26.0';
var getDataURL = UserProperties.getProperty(baseURLPropertyName) + '/services/data/v26.0/query/?q=SELECT+name+from+Account';
var dataResponse = UrlFetchApp.fetch(getDataURL,getUrlFetchOptions()).getContentText();
return dataResponse;
}
////oAuth related code
//hardcoded here for easily tweaking this. should move this to ScriptProperties or better parameterize them
var AUTHORIZE_URL = 'https://login.salesforce.com/services/oauth2/authorize'; //step 1. we can actually start directly here if that is necessary
var TOKEN_URL = 'https://login.salesforce.com/services/oauth2/token'; //step 2. after we get the callback, go get token
var CLIENT_ID = '3MVG9y6x0357HlefXsMa7Fg0tYO_2cKJPxSwvFCvZY9xhPk3rn_vgFaU__ooXuA4qFLqLjCuRyj1q.dXjDSC2';
var CLIENT_SECRET='MY_SECRET_HERE';
var REDIRECT_URL= ScriptApp.getService().getUrl();
//this is the user propety where we'll store the token, make sure this is unique across all user properties across all scripts
var tokenPropertyName = 'SALESFORCE_OAUTH_TOKEN';
var baseURLPropertyName = 'SALESFORCE_INSTANCE_URL';
//this is the URL where they'll authorize with salesforce.com
//may need to add a "scope" param here. like &scope=full for salesforce
function getURLForAuthorization(){
return AUTHORIZE_URL + '?response_type=code&client_id='+CLIENT_ID+'&redirect_uri='+REDIRECT_URL
}
function getAndStoreAccessToken(code){
var nextURL = TOKEN_URL + '?client_id='+CLIENT_ID+'&client_secret='+CLIENT_SECRET+'&grant_type=authorization_code&redirect_uri='+REDIRECT_URL+'&code=' + code;
var response = UrlFetchApp.fetch(nextURL).getContentText();
var tokenResponse = JSON.parse(response);
//salesforce requires you to call against the instance URL that is against the token (eg. https://na9.salesforce.com/)
UserProperties.setProperty(baseURLPropertyName, tokenResponse.instance_url);
//store the token for later retrival
UserProperties.setProperty(tokenPropertyName, tokenResponse.access_token);
}
//this may need to get tweaked per the API you are working with.
//for instance, SLC had content type of application/vnd.slc+json. SLC also allows lower case 'bearer'
function getUrlFetchOptions() {
var token = UserProperties.getProperty(tokenPropertyName);
return {
"contentType" : "application/json",
"headers" : {
"Authorization" : "Bearer " + token,
"Accept" : "application/json"
}
};
}
function isTokenValid() {
var token = UserProperties.getProperty(tokenPropertyName);
if(!token){ //if its empty or undefined
return false;
}
return true; //naive check
//if your API has a more fancy token checking mechanism, use it. for now we just check to see if there is a token.
/*
var responseString;
try{
responseString = UrlFetchApp.fetch(BASE_URI+'/api/rest/system/session/check',getUrlFetchOptions(token)).getContentText();
}catch(e){ //presumably an HTTP 401 will go here
return false;
}
if(responseString){
var responseObject = JSON.parse(responseString);
return responseObject.authenticated;
}
return false;*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment