0

I am using a Tooling API credential to authenticate against the same Salesforce org so that I can get some tooling API data in Apex. I am using oauth 2 and initially my integration user has to go under Setup > Security > Named Credentials > Edit > Save in order to authentcate upon which they are able to access the data.

The issue is when the bearer token expires, I am getting a 401 and a message saying:

[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]

I thought that the named credential handled the refresh token business automatically but that does not seem to be the case.

My Apex code:

Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:Tooling_API_Credential'+'/services/data/v54.0/jobs/query/');   
        req.setHeader('Authorization', 'Bearer ' + '{!$Credential.OAuthToken}');
        req.setHeader('Content-Type', 'application/json');
        req.setMethod('GET');
        HttpResponse res = h.send(req);     
        
        while (res.getStatusCode() == 302) {
                req.setEndpoint(res.getHeader('Location'));
                res = new Http().send(req);
            }
        String issuedAt = null;
        JSONParser jobParser = null;
        Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());

My named credential: enter image description here

My Auth Provider:

enter image description here

As you can see I am using the scopes of full & refresh_token. I also looked at Named Credential: Authentication process and refresh token but that was not much help. I also saw this by Salesforce: https://help.salesforce.com/s/articleView?id=000381864&type=1 but I guess I am not clear whether a dummy call needs to be made (considering I am not using SOAP) or a named credential is smart enough to do it all.

Why is the named credential not handling the automatic refresh token functionality? Please help.

6
  • I dont think you have to explicitly set the Authorization header in your callout if your Named Credential type is of OAuth Apr 3 at 16:05
  • I commented that line out and even without authorization header same error. Apr 3 at 16:19
  • According to this post, it seems like order of scopes provided may also be a contributing factor salesforce.stackexchange.com/a/267542/3901 Apr 3 at 16:40
  • I changed the scope to 'refresh_token full' on both the auth provider and named credential. Still the same 401. Apr 3 at 16:52
  • may have to double check its returning a 401. May want to replicate in POSTMAN and see if you can post the screenshots in this post Apr 3 at 17:40

0

You must log in to answer this question.

Browse other questions tagged .