2

I am trying to call a rest resource within the same org (Because I am inserting records of an object developed by 3rd party and they strongly advised us to not do any DML directly rather they have developed rest resources for any data changes through code). I have named credentials added and a connected app that provides me with consumer Key and client secret, however I get the above error when calling the rest resource with the session id. I am sure I'm being daft, is there something you could spot? (I would use Userinfo.getSessionId() but my version is summer '18)

My code

Http http = new Http();
HttpRequest request = new HttpRequest();
//String Endpoint = 'https://login.salesforce.com/services/oauth2/token';
request.setEndpoint('callout:CIPHR_Kimble/services/oauth2/token');
//request.setEndpoint(Endpoint);
request.setMethod('POST');

String ClientId = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
String ClientSecret = '11111111111111111';
String username = 'User@example.com';
String password = 'Password+SecurityCode';
request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
request.setBody('grant_type=password' + 
              '&client_id=' + ClientId + 
              '&client_secret=' + ClientSecret + 
              '&username=' + username +
              '&password=' + password
           );
HttpResponse response = http.send(request);
// Parse the JSON response
String Access_Token;              
system.debug('body:'+response.getBody());  
JSONParser parser = JSON.createParser(response.getBody());
while (parser.nextToken() != null) {
    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'access_token')) {
        parser.nextToken();
        Access_Token = parser.getText();    
    }
}
system.debug('access token'+Access_Token);

String sfdcURL = URL.getSalesforceBaseUrl().toExternalForm(); 
String restAPIURL = sfdcURL + '/services/apexrest/KimbleOne/v1.0/Import/UpdateResourceCalendar';  
String AccessToken = Access_Token;

HttpRequest httpRequest = new HttpRequest();
//httpRequest.setEndpoint(restAPIURL); 
httpRequest.setEndpoint('callout:CIPHR_Kimble/services/apexrest/KimbleOne/v1.0/Import/UpdateResourceCalendar');
httpRequest.setMethod('POST'); 
httprequest.setHeader('Content-Type', 'application/json');
httprequest.setHeader('Accept','application/json');
httpRequest.setHeader('Authorization', 'OAuth '+Access_Token);        
httpRequest.setHeader('Authorization', 'Bearer '+Access_Token); 

httpRequest.setBody('[{ "CIPHR_Id" : "7648_44573", "hours" : 2.40, "date" : "2018-07-18", "activity" : "a601X0000000030QAA", "resource" : "10187" }]');

System.debug('Access token '+AccessToken);
String responseString = '';
try {  
    Http http1 = new Http();   
    HttpResponse httpResponse = http1.send(httpRequest);  
    System.debug('>> Response of payload >> '+httpResponse.getStatusCode());
    responseString = 'Status Code: '+httpResponse.getStatusCode()+' Response: '+httpResponse.getBody();
} catch(Exception e) {  
    System.debug('ERROR: '+ e.getMessage());  
    responseString = e.getMessage();
}  
System.debug(' ** response ** : ' + responseString );
  • You seem to be setting both OAuth and Bearer authorization type while sending request to your rest api. Try removing OAuth and that should typically work. – Jayant Das Oct 1 '18 at 1:39
  • @JayantDas I tried it before posting the question still no luck! – SFDC_Dev Oct 1 '18 at 6:34
2

There was a talk on using Named Credentials to call back into the same Salesforce org at Dreamforce this year 2018: Named Credentials: Securing and Simplifying API Callouts. Looks like it was the same talk as 2017

The example was given against the SOAP Metadata API, but the general principal should be the same. You can use the {!$Credential.OAuthToken} directly for the Authorization Bearer header. Just make sure you setup your Named Credential using OAuth Authentication to start with rather than password authentication.

There is a longer worked example in Using Named Credentials with the Apex Wrapper Salesforce Metadata API (apex-mdapi).

You would end up with something like:

HttpRequest httpRequest = new HttpRequest();
httpRequest.setEndpoint('callout:CIPHR_Kimble/services/apexrest/KimbleOne/v1.0/Import/UpdateResourceCalendar');
httpRequest.setMethod('POST'); 
httprequest.setHeader('Content-Type', 'application/json');
httprequest.setHeader('Accept','application/json');
httpRequest.setHeader('Authorization', 'Bearer {!$CIPHR_Kimble.OAuthToken}'); 

For Salesforce REST endpoints you only need to set the Authorization Bearer.

-1

You need to correct your Authorization value like :- Bearer 00D3F000000 ...Provide space after "Bearer" then your access_token

  • 2
    Sorry, your answer is not correct. The above marked answer by Daniel is correct! – SFDC_Dev Jun 21 at 17:16

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.