Hi I am trying to connect one salesforce org to another but getting below error in response body while trying to get the access token using the username password flow in oauth. Please suggest what is wrong in my code.

{"error":"invalid_grant","error_description":"authentication failure"}

Here is my Code

String endpoint='https://pselectronicss-dev-ed.my.salesforce.com/services/oauth2/token';

String username     = 'xxxxxxxxxx'; 
String password     = 'xxxxxxxx';
String ClientId     = 'xxxxxxxxxxxxxxxxPj2pFpmu9DULaS1kvcJno_OvLRWkK1';
String ClientSecret     = 'XXXXX50EEACD25542C6D33082CA5B'; 

Httprequest req = new HttpRequest();    

req.setBody('grant_type=password' + 
      '&client_id=' + ClientId + 
      '&client_secret=' + ClientSecret + 
      '&username=' + username +
      '&password=' + password


Http http = new Http();

HttpResponse res;
String Access_Token;
try {
    res = http.send(req);                
    JSONParser parser = JSON.createParser(res.getBody());
    while (parser.nextToken() != null) {
        if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'access_token')) {
            Access_Token = parser.getText();    
}catch(system.CalloutException e){            
system.debug('access token'+Access_Token);
  • 1
    Have you considered using Named Credentials? take a look a Named Credentials as Callout Endpoints – Robs Apr 27 '19 at 13:36
  • Make sure your connected app has been configured properly. – Avijit Apr 27 '19 at 20:56
  • Did you append the security token to your password? – RedDevil Apr 28 '19 at 6:05
  • @Robs I did create named credentials and this error is not there but I still did not get the access token. That is still null. – Pushpendra Karasi Apr 29 '19 at 4:37

Please check your credentials part. Error suggests that either username or password is not provided correct.

Password should have the Security Token appended unless IP is white listed in the target org.

  • I am trying to established a connection and get an access token in my code for further processing. – Pushpendra Karasi Apr 29 '19 at 5:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.