0

So there are already many questions and answers about this error online already and I have looked through them all over and over and i cannot overcome the problem.

I am creating an LWC to get debug logs to display them in a user friendly way in the utilities bar. I have some test code which when run from execute anonymous returns logs but when run from an LWC returns {"message":"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}. Here is the code:

@AuraEnabled
    public static void getLogs() {
        List<ApexLog> logs = [SELECT Id FROM ApexLog LIMIT 1];
        String token = getToken();
        String baseUrl = URL.getSalesforceBaseUrl().toExternalForm()
        + '/services/data/v28.0/';
    
        HTTPRequest req = new HTTPRequest();
        req.setEndpoint(baseUrl + 'sobjects/ApexLog/' + logs[0].Id + '/Body');
        req.setMethod('GET');
        req.setHeader('Authorization', 'Bearer ' + token);
        req.setHeader('Content-Type', 'application/json');
    
    
        Http h = new Http();
        HttpResponse res = h.send(req);

        List<String> all = res.getBody().split('\n');
        for (String line : all) {
            System.debug(line);
        }
    }
    public static String getToken() {
        String key = 'xyz';
        String secret = 'abc';
        String username = '[email protected]';
        String password = '123';
        HTTPRequest request = new HTTPRequest();
        request.setEndpoint('https://login.salesforce.com/services/oauth2/token');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        request.setBody(
            'grant_type=password' +
            '&client_id=' + key +
            '&client_secret=' + secret +
            '&username=' + username +
            '&password=' + password
        );
        Http http = new Http();
        HttpResponse response;

        Token token = new Token();

        try {
            response = http.send(request);
            System.debug('body: ' + response.getBody());
            token = (Token )JSON.deserialize(response.getBody(), Token.class);
        } catch(System.CalloutException error){
            System.debug('error: ' + error);
        }
        System.debug('access token: ' + token);
        return token.access_token;
    }

    public class Token{
        public String access_token = '';
    }

The LWC is currently just simply a button that calls getLogs(). I am a system admin with API enabled. I have enabled "Allow OAuth Username-Password Flows" as well.

Can anyone help? Thanks and best regards, Dane

2
  • What kind of org is this?
    – identigral
    Commented Oct 2, 2023 at 14:49
  • @identigral It is a dev hub org.
    – Dane
    Commented Oct 4, 2023 at 5:58

2 Answers 2

0

Note that Salesforce has OAuth 2.0 Username-Password Flow Blocked by Default in New Orgs. Make sure that you enable "Allow OAuth Username-Password Flows" in the "OAuth and OpenID Connect Settings" in Setup. Also, make sure the scope for the Connected App includes "Full" or "API" access, as appropriate.

It may be easier to just create a Named Credential and use that in your code, instead. This will decrease the number of logins that will be logged against the org you're calling and make it easier to fix authentication if the user session disappears for some reason.

1
  • Thanks for the reply. I should have mentioned i have enabled 'allow username-password flow' and I have provided the connected app will 'full' access. I tried setting up named credentials now but now i get "This session is not valid for use with the REST API" from both execute anonymous and the LWC.
    – Dane
    Commented Oct 2, 2023 at 13:58
0

In my request header I was missing an additional Authorization attribute.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .