function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nikhil Shrigod 25Nikhil Shrigod 25 

Unable to retrive the access token while doing a callout for Apex REST API which is present in another salesforce org.

public class SendAccountUsingRESTAPI {
  private final String clientId = 'XXXX';
   private final String clientSecret = 'XXXX';
   private final String username = 'XXXX';
   private final String password = 'XXXX';
  public class deserializeResponse
   {
      public String id;
      public String access_token;
   }
  public String ReturnAccessToken (SendAccountUsingRESTAPI acount)
   {
      String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
     Http h = new Http();
      HttpRequest req = new HttpRequest();
      req.setBody(reqbody);
      req.setMethod('POST');
      req.setEndpoint('https://ap4.salesforce.com/services/oauth2/token');
      HttpResponse res = h.send(req);
     deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
     system.debug('@@@@access_token@@ = '+resp1 );
      return resp1.access_token;
   }
}

In this class I am trying to get the access token with the help of ReturnAccessToken() method. But due to some reason it is returning null. I am not getting the access token. All the details I get is Status code = 400 and Status = Bad request. Can anyboody please give a solution to this problem, because I've got stuck here for a long time.
v varaprasadv varaprasad
Hi Nikhil,

You need to add a security token along with the password.

More Info: 
https://www.youtube.com/watch?v=7PaDtgPLH90

After watching this video still if you have an issue please let me know I will help you.

Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.


Salesforce Freelance Consultant/Developer/Administrator/Trainer
@For Salesforce Project Support: varaprasad4sfdc@gmail.com


Salesforce latest interview questions and training videos :
https://www.youtube.com/channel/UCOcam_Hb4KjeBdYJlJWV_ZA?sub_confirmation=1


Thanks
Varaprasad





 
v varaprasadv varaprasad
In request you need to add header also.

req.setheader('content-type' : 'application/x-www-form-urlencoded');
Nikhil Shrigod 25Nikhil Shrigod 25
thanks for replying V Varaprasad.
Nikhil Shrigod 25Nikhil Shrigod 25
Hello V Varaprasad I tried putting req.setheader('content-type' : 'application/x-www-form-urlencoded');
and I also saw your video but still I am getting token = null.
Even in postman it is giving :
{
    "error": "invalid_grant",
    "error_description": "authentication failure"
}
Nikhil Shrigod 25Nikhil Shrigod 25
can you please tell me that is there anything wrong with call back  URL in connected app or Remote site settings?