2

I have created Connected App & Auth Provider.
This is the Code i am currently running. Getting error. What I am doing wrong?
Can anyone please help me with this?

1st Org - (Class which will get 10 Account details)

@RestResource(urlMapping='/v1/getAccounts/*')
global with sharing class FetchAccount {
@HttpGet
    global static list<account> fetchAccount(){
        RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        List<account> listAccount =[Select Id , Name from Account LIMIT 10 ];
        return listAccount ;
    }
}

2nd Org - (REST API which is calling method from 1st Org)

public class AccountRestExampleConsumeFromOtherSFOrg{

public String AccountRestExampleConsumeFromOtherSFOrg(){

String endpoint='https://login.salesforce.com/services/oauth2/token';

String username = '*******'; 
String password = '********';
String ClientId= '********************';
String ClientSecret = '***************'; 

Httprequest req = new HttpRequest();    
req.setMethod('POST');    
//req.setHeader('Content-Type','application/json');

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

req.setEndpoint(endpoint);
//req.setHeader('Authorization', 'OAuth '+UserInfo.getSessionId());
Http http = new Http();
HttpResponse res;       
String Access_Token;
try {
res = http.send(req);                
system.debug('body:'+res.getBody());  
JSONParser parser = JSON.createParser(res.getBody());
while (parser.nextToken() != null) {
    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'access_token')) {
            parser.nextToken();
            Access_Token = parser.getText();    
            } 
    }            
}catch(system.CalloutException e){            
system.debug('error'+e);
}
system.debug('access token'+Access_Token);
Httprequest req1 = new HttpRequest();  
req1.setEndpoint('https://einsteinpersi-dev- 
ed.my.salesforce.com/services/apexrest/v1/getAccounts');  
req1.setMethod('GET');    
req1.setHeader('Content-Type','application/x-www-form-urlencoded');
req1.setHeader('Authorization','Bearer '+Access_Token);            
Http http1 = new Http();
HttpResponse res1 = http1.send(req1);                 
system.debug('body11:'+res1.getBody()); 
return res1.getBody();
}
}

Error I am getting - enter image description here

4
  • What error are you receiving, verbatim, and on which line? Please add this to your question via an edit.
    – David Reed
    Dec 27, 2018 at 12:29
  • 1
    Can you try by removing + after password in this line req.setBody('grant_type=password
    – Reshma
    Dec 27, 2018 at 12:42
  • @Reshma Removed +, but still same error. One is grant_type problem and also access token is null
    – user62549
    Dec 27, 2018 at 14:08
  • @MohitKulkarni This is a community site; the best way for you to ensure you get help is to write a detailed, high-quality question. It's not really productive to try to tag specific people in with comments.
    – David Reed
    Dec 27, 2018 at 14:45

4 Answers 4

1

There are 2 things wrong in your callout in 2nd org.

  1. Set body is not proper,

    req.setBody('grant_type=password&client_id=' + ClientId + '&client_secret=' + ClientSecret + '&username=' + username +'&password=' + password); 
    
  2. You don't have to set Authorization header as Session ID from Source org to get access token. Remove that.

Src: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_username_password_oauth_flow.htm

6
  • I did the changes, but still getting same errors.
    – user62549
    Dec 27, 2018 at 14:06
  • Is other org sandbox or Prod? Based on that login url(endpoint) will change Dec 27, 2018 at 14:17
  • No both are Prod (Developer Edition)
    – user62549
    Dec 27, 2018 at 14:27
  • Do you have code where you have successfully executed this type of requirement?
    – user62549
    Dec 27, 2018 at 14:29
  • I dont have a handy code, but I followed this: salesforce.stackexchange.com/questions/25021/… Dec 27, 2018 at 14:33
1

Finally understood what was the issue. Solved the problem.
Although, the error it was showing was - "Invalid grant_type", actually I was not able to call API in another Org because 'Access Token' wasn't getting generated.

Answer - I had to append my Org's "Security Token" with my Org password....!!!!!

Till now I was only passing Org password in req.setBody().
Rest of the code absolutely correct & no changes required.

1

You must append the user’s security token to their password A security token is an automatically-generated key from Salesforce. For example, if a user's password is mypassword, and their security token is XXXXXXXXXX, then the value provided for this parmeter must be mypasswordXXXXXXXXXX. For more information on security tokens see “Reset Your Security Token” in the online help.enter link description here

0

Update your setBody method by

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

Refer the format here: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_username_password_oauth_flow.htm

1
  • I found the answer...Have posted it
    – user62549
    Jan 8, 2019 at 17:32

You must log in to answer this question.