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
rafaferrerrafaferrer 

INVALID SESSION ID - This session is not valid for use with the REST API

Hello,

 

I've obtained an access token via OAuth. When I use that access token to make a call to a custom Apex REST class I receive the error below:

 

[{"message":"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}]

 

The strange thing is if I try to get a session ID using an username/password with SOAP API, I receive a valiad session ID and I am able to use it in my application. For security reasons, I don´t wat to store username and password in my app, so I am going to the OAuth Authentication.

 

Below are the steps that I am following to authorize the access: (I have omitted the last characters of the tokens and codes.)

 

1) Get the authorization code: 

https://na15.salesforce.com/services/oauth2/authorize?response_type=code&client_id=3MVG9A2kN3Bn17htJ...

&redirect_uri=https://www.exior.com.br

 

2) Get the session ID and refresh token: (Method POST)

 

Request:

 

Endpoint:

https://na15.salesforce.com/services/oauth2/token

 

Header:

Content-type: application/x-www-form-urlencoded

 

Body:

grant_type=authorization_code&code=aPrxMZkm7lCkgfTjSLFeTxyHVa55QG9Gpj8v6YpU6QMRHwCgwpcOuVi5feu66Rcn4IDpaXXXXX%3D%3D&client_id=3MVG9A2kN3Bn17htJkkaw42HqCS3pFMwu7ccGARiPuX.LpTrz9D1x4ugq_DHyPSTPP2botyAx8c.02.YXXXXX &client_secret=77219427916XXXXXXXX&redirect_uri=https://www.exior.com.br

 

Response:

 

<Response xmlns="https://na15.salesforce.com/services/oauth2/token">

<access_token>00Di0000000abPx!AQYAQM4Nyzez6GRtdtn0L76pjODKcgZJY.jKWZ.QeM60uuffkZyIMH_AS8pokvWSAMm8JY5K6DaiqM9ISd64MyjjMKjXXXXX</access_token> <id>https://login.salesforce.com/id/00Di0000000abPxEAI/005i0000000w9RpAAI</id>

<instance_url>https://na15.salesforce.com</instance_url>

<issued_at>1373031879062</issued_at> <refresh_token>5Aep861z80Xevi74eUm_l7LnvGMm1nrPXfF_JmNfABiGpb0DBP6O4qSboHB9ZZnxpUeErpFgrQl5So9ZgMXXXXX</refresh_token> <scope>refresh_token</scope>

<signature>FRS81Y6zTT5kMinx0SZugV18POV4VwQOg1KgXTyXXXXX</signature> </Response>

 

3) Use the refresh token to get a new session ID: (Method POST)

 

Request:

 

Endpoint:

https://na15.salesforce.com/services/oauth2/token

 

Header:

Content-type: application/x-www-form-urlencoded

 

Body: 

grant_type=refresh_token&client_id=3MVG9A2kN3Bn17htJkkaw42HqCS3pFMwu7ccGARiPuX.LpTrz9D1x4ugq_DHyPSTPP2botyAx8c.02.YXXXXX&client_secret=77219427916XXXXXXXX&refresh_token=5Aep861z80Xevi74eUm_l7LnvGMm1nrPXfF_JmNfABiGpb0DBP6O4qSboHB9ZZnxpUeErpFgrQl5So9ZgMXXXXX

 

Response:

 

<Response xmlns="https://na15.salesforce.com/services/oauth2/token"> <access_token>00Di0000000abPx!AQYAQM4Nyzez6GRtdtn0L76pjODKcgZJY.jKWZ.QeM60uuffkZyIMH_AS8pokvWSAMm8JY5K6DaiqM9ISd64MyjjMKjXXXXX</access_token> <id>https://login.salesforce.com/id/00Di0000000abPxEAI/005i0000000w9RpAAI</id> <instance_url>https://na15.salesforce.com</instance_url> <issued_at>1373031978095</issued_at> <scope>refresh_token</scope> <signature>Nf210fXLTsUkWAaE3ACeo8KprYaEFOHs3psVgLyXXXXX</signature> </Response>

 

When I try to use the session ID received with the "authorization_code call" or"refresh_token call" I receive the error [{"message":"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}].

 

 

Below is how I am using this session id in my application:

 

public String ValidaCredenciais(String Usuario, String Senha, String SessionId) {

        

HttpRequest req = new HttpRequest();         

Http http = new Http();         

req.setMethod('POST');         

req.setEndpoint('https://na15.salesforce.com/services/apexrest/validalogin');         

req.setBody('{"usuario": "' + Usuario + '", "senha": "' + Senha + '", "orgId": "' + System.Userinfo.getOrganizationId() + '"}');

req.setHeader('Content-Type', 'application/json');

req.setHeader('Authorization', 'OAuth ' + SessionId);

 

HTTPResponse resp = http.send(req);

String RetornoValida = resp.getBody();    

 

return RetornoValida;

 

}

 

 

Vinita_SFDCVinita_SFDC

Hello,

 

Please try to get session id as follows:

 

req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());

You can get the SessionId of the logged in user as UserInfo.getSessionId().

 

Hope this helps!

Pratibha SundaramoorthyPratibha Sundaramoorthy
Hi,

I'm trying to make REST API Call to access UI-API by the following code from my lightning page as follows, 

Http http = new Http();
HttpRequest request = new HttpRequest();
String shost = System.Url.getSalesforceBaseURL().toExternalForm();
request.setEndpoint(shost + relativeURL);
request.setMethod('GET');
request.setHeader('Authorization', 'OAuth '+ UserInfo.getSessionId());
try {
        response = http.send(request);
        } Catch(System.Exception e) {
            System.debug('ERROR: '+e);
            throw e;
   }

I was able to retrieve data in my dev console from execute anonymous window when I call this function. But when I use it in inside my app ( The call is done from a lightning page), it gives the following error as response:

{"message":"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}

Any idea why this is happening and how to solve it?
 
Mariia IllarionovaMariia Illarionova
Got exactly the same problem as Pratibha Sundaramoorthy/
Does anyone know the solution?
Pratibha SundaramoorthyPratibha Sundaramoorthy
Hi Maria Illarionova, are you calling the apex call out method from lightning? If yes, then you might need to create a named credential to use it. 
Helpful links, 
Salesforce documentation (https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/apex_api_calls.htm)
El Toro's example to create named credential (https://eltoro.secure.force.com/ETLC_APIsFromApex)
Rajvakati's example to create named credential (https://rajvakati.com/2018/01/28/salesforce-ui-api-lightning-examples/)
Hope this helps.
Ross GaidukevychRoss Gaidukevych
rafaferrer, you should define 'scope' parameter in your request uri like this : https://na15.salesforce.com/services/oauth2/authorize?response_type=code&client_id=3MVG9A2kN3Bn17htJ...&redirect_uri=https://www.exior.com.br&scope=api+web+refresh_token
after this, try again and use access_token with the rest api. Good luck)
test org 65test org 65
I have get refresh token like @rafaferrer have written above code but when i use this refresh token in my jave code to call custom rest api then it show the following error:-
{"message":"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}
Plz help how could i sove this.
david wolardavid wolar
resolved my issue blogger at : ptcl (https://ptclbill.net/)