You need to sign in to do that
Don't have an account?
Get token from salesforce oauth2 in apex, having no hardcoded values for authentication
Hello everyone. I have a security question to make. So I am viewing a prospect from pardot through the pardot API from my apex code. Everything works great I have no issues with the implementation. Initially, I make a request to https://login.salesforce.com/services/oauth2/token, so i can receive a token that I need to access pardot API. I do this using the following keys in my request:
grant_type --> password
client_id --> "the client id i get from connected app I have created"
client_secret -->"the client secret i get from connected app I have created"
username --> "username of org of the connected app I have created"
password --> " password of org of the connected app I have created"
The problem is that I pass these values hardcoded directly in my apex code (username, password , client_secret, client_id) Wich I know is not a good practice, and also it would cause problmes when for example the administrator will change the password of the org of the connected app.
I need a way for those values to be inserted elsewhere and not be visible inside my apex code. I have found something about named requests and auth. providers but I cannot understad clearly what I have to do. Whould be a good solution to create a custom object and insert the values there with encryption o I can decrypt them in the code?
how I get the Token:
public static String getToken(){
Http http = new Http();
HttpRequest request = new HttpRequest();
String body = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+userName+'&password='+password;
request.setEndpoint('https://login.salesforce.com/services/oauth2/token');
request.setMethod('POST');
request.setBody(body);
HttpResponse response = http.send(request);
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
if(response.getStatusCode() == 200){
String token = (String)results.get('access_token');
return token;
}else{
throw new CalloutException('FAILED TO GET TOKEN');
}
After receiving the Token I make an Http Request to pardot:
HttpRequest request = new HttpRequest();
request.setEndpoint('https://pi.pardot.com/api/prospect/version/4/do/read?email='+email+'&format=json');
request.setMethod('POST');
request.setHeader('Authorization', 'Bearer ' + token);
request.setHeader('Pardot-Business-Unit-Id', unitId);
HttpResponse response = http.send(request);
Thank you in Adcance!!