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