0

To integrate SF with PowerBI we first need to get an access token from Azure AD with the powerBI scope. I am able to set up a named credential (per user) which connects to Azure AD, I am able to reuse the {!credential.OAuthToken} in subsequent requests I used for testing purposes. However, is there a way to actually store this OAuthToken in a variable in apex to return it to my LWC? The PowerBI.js library needs the Azure AD token explicitly to embed a report, so my idea was to return it by my apex controller.

Another option is to not use named credentials and perform the OAuth2 handshaking myself but this brings additional complexity and work.

Any hints are appreciated at this point.

1

1 Answer 1

1

Yes, you can store the OAuth token in an Apex variable and return it to your LWC component. Here's how you can do it:

  1. In your Apex controller, make a call to retrieve the OAuth token using the named credential and store it in a variable:
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:YourNamedCredential/token');
req.setMethod('GET');
HttpResponse res = h.send(req);
String oauthToken = res.getBody();
  1. Return the token to your LWC component by including it in the response from the Apex method:
@AuraEnabled
public static String getOAuthToken() {
    // Retrieve the OAuth token as described above
    // ...
    return oauthToken;
}
  1. In your LWC component, call the Apex method to retrieve the token and use it to initialize the PowerBI.js library:
import { LightningElement, track, wire } from 'lwc';
import { getOAuthToken } from '@salesforce/apex/YourApexController.getOAuthToken';

export default class YourLWCComponent extends LightningElement {
    @track token;

    @wire(getOAuthToken)
    wiredToken({ error, data }) {
        if (data) {
            this.token = data;
            // Initialize the PowerBI.js library with the retrieved token
            // ...
        } else if (error) {
            // Handle the error
            // ...
        }
    }
}
1
  • In my question I am implying that the retrieval of the access token is implicitly done by the Named Credential setup after the user has granted access via the 'External Credentials' section in 'Settings'. So I don't explicitly do a callout for the token, it's managed internally in SF.
    – voluminat0
    Commented Feb 3, 2023 at 14:45

You must log in to answer this question.

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