0

I am calling a method imperatively from lwc and its not giving the same result when I am calling same code though anonymous block. Below is my class and when I am calling the method from anonymous block its giving response as System.HttpResponse[Status=OK, StatusCode=200] but while running from lwc its giving System.HttpResponse[Status=Unauthorized, StatusCode=401].

public with sharing class MessageController {
    @AuraEnabled
    public static Integer fetchUnreadMessages(){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        HttpResponse response = new HttpResponse();
        request.setEndpoint('https://'+URL.getSalesforceBaseUrl().getHost()+'/services/data/v48.0/chatter/users/'+UserInfo.getUserId()+'/conversations/unread-count');
        request.setMethod('GET');
        string autho = 'Bearer '+userInfo.getSessionId();
        request.setHeader('Authorization', autho);
        response = http.send(request);
        if (response.getStatusCode() == 200) {
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            system.debug('****RESPONSE::'+results.get('unreadCount'));
            return Integer.valueOf(results.get('unreadCount'));
        }
        return 0;
    }
}

2 Answers 2

4

The Lightning Session ID doesn't include REST API privileges, except for a few UI-API calls. You should be able to use the ConnectApi classes to get the information you want for Chatter, or you can use a Named Credential to allow Apex access to the API.

0

You also have the option to get sessionId from VF page.

Define a VF page

<apex:page contentType="application/json">
    {!$Api.Session_ID}
</apex:page>

then in your apex add a method to get the session id from the vf page

   public static String getSessionIdFromVFP() {
        return Page.SessionIdFromVFP.getContent().toString();
    }

And in your fetchUnreadMessages method call getSessionIdFromVFP to get the session id.

    string autho = 'Bearer '+getSessionIdFromVFP();
    request.setHeader('Authorization', autho);
    response = http.send(request);

You must log in to answer this question.

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