I have a Python program that performs a REST API call:
def get_token(self):
try:
target_url = 'http://auth-{0}-{1}.{2}{3}/token'.format(
self.country,
self.environment,
self.domain_pref,
self.domain
)
payload = {
'username': keys[self.project][self.environment]['username'],
'password': keys[self.project][self.environment]['password'],
'client_id': keys['client_id'],
'client_secret': keys['client_secret'],
'grant_type' : 'password'
}
headers = {'Cache-Control': 'no-cache'}
response = requests.post(target_url, data=payload,headers=headers)
token = '{0} {1}'.format('Bearer',response.json()['access_token'])
return token
except Exception as e:
logging.error(response.status_code)
logging.error(response.content)
raise e
I translated the Python program to Apex. Running the Apex code returns 400:
// oAuth2 client credentials
String username = '[email protected]';
String password = 'password';
String clientId = 'myclientid';
String clientSecret = 'myclientsecret';
String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
// AP token endpoint setup
String tokenAPEndpoint = 'http://auth-{0}-live.mydomain.com/token';
String formattedTokenEndpoint;
String token;
String[] formatArgumentsToken = new String[]{'mx'};
formattedTokenEndpoint = String.format(tokenAPEndpoint, formatArgumentsToken);
System.debug('URL ' + formattedTokenEndpoint);
HttpRequest requestToken = new HttpRequest();
requestToken.setEndpoint(formattedTokenEndpoint);
requestToken.setHeader('Content-Type','application/json');
requestToken.setBody(reqbody);
requestToken.setMethod('POST');
system.debug('grant_type set to:' + requestToken.getHeader('grant_type'));
system.debug('client_secret set to:' + requestToken.getHeader('client_secret'));
system.debug('username set to:' + requestToken.getHeader('username'));
Http httpGetToken = new Http();
HttpResponse responseToken = httpGetToken.send(requestToken);
system.debug('Response' + responseToken);
system.debug('notification body' + responseToken.getBody());
Any help as to how this supposed to be done would be greatly appreciated!