[SalesForce] INVALID_SESSION_ID error when external app is calling GETmethod on salesforce

I have created webservice class with Get method.
I have created Connected app and I have consumer key and consumer secret.But I don't have knowledge on how to use it.

When external app is calling they are getting <errorCode>INVALID_SESSION_ID</errorCode> <message>Session expired or invalid</message> .

How can I resolve this error.

Best Answer

First you need to get the access token from the Connect app tokens.

Here is a sample code for your reference

public class oAuth_Controller{

private auth_response rt;

public pagereference auth_Step_1(){


    String auth_url = 'https://login.salesforce.com/services/oauth2/authorize';
    String params =  
                        '?response_type=code' +
                        '&client_id=' + encodingUtil.urlencode('YOURCLIENTID','UTF-8') +
                        '&redirect_uri=https://login.salesforce.com/apex/{YOURVFPAGE}' +                           '&prompt=consent' + 
                        '&scope=' + encodingUtil.URLEncode('full refresh_token','UTF-8') +
                        '&state=step2';
        pageReference pr = New PageReference(auth_url + params);
        return pr;
}

public pagereference auth_Step_2(){

    if(apexPages.currentPage().getParameters().get('state') != 'step2')
        return null;


    HttpRequest req = new HttpRequest();
    Http http = new Http();

    String auth_url = 'https://login.salesforce.com/services/oauth2/token';
    String params =  
                        '?code=' + apexPages.currentPage().getParameters().get('code') +
                        '&grant_type=authorization_code' + 
                        '&client_id=' + encodingUtil.urlencode('YOURCLIENTID','UTF-8') +
                        '&client_secret=YOURSECRET' + 
                        '&redirect_uri=https://login.salesforce.com/apex/YOURVFPAGENAME';

    req.setMethod('POST');
    req.setEndpoint(auth_url + params);

    HTTPResponse resp = http.send(req);

    rt = (auth_response)json.deserialize(resp.getBody(),auth_response.class);
    //Do something with the results
    return null;

}

public void getnewtoken(){

    HttpRequest req = new HttpRequest();
    Http http = new Http();

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

                        '?grant_type=refresh_token' + 
                        '&client_id=' + encodingUtil.urlencode('YOURCLIENTID','UTF-8') +
                        '&client_secret=YOURSECRET' + 
                        '&refresh_token=' + encodingUtil.URLEncode(YOURREFRESHTOKEN,'UTF-8');

    req.setMethod('POST');
    req.setEndpoint(auth_url + params);

    HTTPResponse resp = http.send(req);


}



private class auth_response{

    public string refresh_token;
    public string access_token;

}
}

<apex:page controller="oAuth_Controller" action="{!auth_step_2}">
  <apex:form >
  <apex:commandButton action="{!auth_step_1}" value="Start oAuth" rerender="msgs"/>
  <apex:commandButton action="{!getNewToken}" value="Get new Token" rerender="msgs"/>
  </apex:form>

  <apex:outPutPanel id="msgs">
      <h1>Congratulations</h1>
      {!$CurrentPage.parameters.access_token}
  </apex:outPutPanel>
</apex:page>

Now using this access token you need to make request to your custom Rest endpoint then you will get expected details.

Your sample code would be

curl -H "Authorization: Bearer sessionId" "https://instance.salesforce.com/services/apexrest/MyRestContextExample/"
  • Replace sessionId with the element that you noted in the login response.
  • Replace instance with your element.
  • Replace accountId with the ID of an account which exists in your organization.

Step Two: Set Up Authorization

Oauth Implementation

Related Topic