Last active
January 26, 2022 12:23
-
-
Save lkatney/71dcc4faee856bce1bf85a226596998f to your computer and use it in GitHub Desktop.
NamedCredentailsExample is in Source org with named credentials to hit target salesforce org. NamedCredentailsLogCapture is in target org to handle incoming requests
This file contains 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
public class NamedCredentailsExample { | |
public static String oAuth_flow(){ | |
return makeCallout('OAuth_flow_Demo/services/apexrest/namedcredentials/demo','GET', null,null); | |
} | |
public static String oAuth_flow_Post(String body){ | |
return makeCallout('OAuth_flow_Demo/services/apexrest/namedcredentials/demo','POST', null,body); | |
} | |
public static String salesforce_password_flow(){ | |
Map<String, String> headers = new Map<String, String>{'X-Username' =>'targetusername', 'X-Password' => 'targetpassword'}; | |
return makeCallout('Salesforce_Password_Flow_Demo/services/apexrest/namedcredentails/demo', 'GET',headers,null); | |
} | |
public static String password_flow(String body){ | |
return makeCallout('Password_Flow_Demo/namedcredentails/demo', 'POST', null, body); | |
} | |
private static String makeCallout(String namedcredentails, String method, Map<String, String>headers, String body){ | |
HttpRequest req = new HttpRequest(); | |
req.setEndpoint('callout:'+namedcredentails); | |
if(headers != null){ | |
for(String key : headers.keySet()){ | |
req.setHeader(key, headers.get(key)); | |
} | |
} | |
// req.setHeader('Authorization', 'OAuth {!$Credential.OAuthToken}'); | |
req.setHeader('Content-Type', 'application/json'); | |
req.setMethod(method); | |
req.setBody(body); | |
Http http = new Http(); | |
HTTPResponse res = http.send(req); | |
return res.getBody(); | |
} | |
} |
This file contains 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
@RestResource(urlMapping='/namedcredentials/demo') | |
global class NamedCredentailsLogCapture { | |
@HttpGet | |
global static String getInformation() { | |
return UserInfo.getUserName(); | |
} | |
@HttpPost | |
global static String captureLogs() { | |
RestRequest req = RestContext.request; | |
try{ | |
NamedCredentailsLogCapture.addLog(String.valueOf(req.headers), req.requestBody.toString()); | |
}catch(Exception e){ | |
} | |
return null; | |
} | |
public static void addLog(String headers, String body){ | |
Named_Credentails_Log__c log = new Named_Credentails_Log__c(); | |
log.Body__c = body; | |
log.Headers__c = headers; | |
insert log; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Named credentials sample code