Skip to content

Instantly share code, notes, and snippets.

@sfboss
Created September 7, 2022 01:34
Show Gist options
  • Save sfboss/d4871a9b498da428b49ccaa313e2bd87 to your computer and use it in GitHub Desktop.
Save sfboss/d4871a9b498da428b49ccaa313e2bd87 to your computer and use it in GitHub Desktop.
OAuth generic handler to get access token and parse based on key/secret and credentials hardcoded or custom setting'ed
public class RRSign_OAUTH_Handler implements Schedulable, Database.AllowsCallouts {
public void execute(SchedulableContext SC){
run();
}
@future(callout=true)
public static void run(){
String endpoint = 'https://test.salesforce.com/services/oauth2/token';
// or use this endpoint for a sandbox org:
// String endpoint='https://test.salesforce.com/services/oauth2/token';
String username = ' ';
String password = ' ';
String CONSUMER_ID = ' ';
String CONSUMER_SECRET = ' ';
Httprequest request = new HttpRequest();
request.setMethod('POST');
request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
request.setBody('grant_type=password' +
'&client_id=' + CONSUMER_ID +
'&client_secret=' + CONSUMER_SECRET +
'&username=' + username +
'&password=' + password);
request.setEndpoint(endpoint);
Http http = new Http();
HttpResponse response;
String accessToken;
try{
response = http.send(request);
System.debug('body: ' + response.getBody());
accessToken = parseResponseForAccessToken(response.getBody());
} catch (System.CalloutException error){
System.debug('error: ' + error);
}
System.debug('access token: ' + accessToken);
// be careful as the following line will print sensitive credentials to the logs
// System.debug(UserInfo.getOrganizationId().substring(0, 15) + ' ' + UserInfo.getSessionId().substring(15));
updateCustomSetting(accessToken);
}
public static void updateCustomSetting(String newToken){
CustomSetting__c rrs = [SELECT Id FROM CustomSetting__c WHERE Name = 'SOME_NAME' LIMIT 1];
rrs.Access_Token__c = newToken;
update rrs;
}
private static String parseResponseForAccessToken(String responseBody){
String accessToken;
JSONParser parser = JSON.createParser(responseBody);
while (parser.nextToken() != null){
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'access_token')){
parser.nextToken();
accessToken = parser.getText();
}
}
return accessToken;
}
private static void query(String accessToken){
// this endpoint allows us to append a SOQL query to retrieve specific data
// see the documentation for a complete list of endpoints
String endpoint = 'https://yourinstance.salesforce.com/services/data/v20.0/query/?q=SELECT+name+from+account+limit+1';
Httprequest request = new HttpRequest();
Http http = new Http();
HttpResponse response;
request.setEndpoint(endpoint);
request.setMethod('GET');
// we can use either of the two below lines for content Type.
// request.setHeader('Content-Type','application/json');
request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
request.setHeader('Authorization', 'Bearer ' + accessToken);
response = http.send(request);
// => {"totalSize":1,"done":true,"records":[{"attributes":{"type":"Account","url":"/services/data/v20.0/sobjects/Account/0014000000xVKZgAAO"},"Name":"Jane Doe"}]}
System.debug('body: ' + response.getBody());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment