0% found this document useful (0 votes)
80 views

Power BIEmbedded

The document describes the process for embedding Power BI reports into an application using the Power BI Embedded service. It includes code for authenticating with Azure Active Directory (AAD) to retrieve an access token, and then using that token to embed a report by initializing an iframe and loading the report configuration. The code handles both master user and service principal authentication, and refreshes tokens silently from cache if possible. On the server, it includes an Express route to generate embed tokens based on a requested report.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views

Power BIEmbedded

The document describes the process for embedding Power BI reports into an application using the Power BI Embedded service. It includes code for authenticating with Azure Active Directory (AAD) to retrieve an access token, and then using that token to embed a report by initializing an iframe and loading the report configuration. The code handles both master user and service principal authentication, and refreshes tokens silently from cache if possible. On the server, it includes an Express route to generate embed tokens based on a requested report.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Esquema de uso PBIE para clientes


Paso a Producción


3. Código

const getAuthenticationToken = async function() {

// Use ADAL.js for authentication


let adal = require("adal-node");

let AuthenticationContext = adal.AuthenticationContext;

// Create a config variable that store credentials from config.json


let config = require(__dirname + "/../config/config.json");

let authorityUrl = config.authorityUri;

// Check for the MasterUser Authentication


if (config.authenticationMode.toLowerCase() === "masteruser") {
let context = new AuthenticationContext(authorityUrl);

return new Promise(


(resolve, reject) => {
context.acquireTokenWithUsernamePassword(config.scope, co
nfig.pbiUsername, config.pbiPassword, config.clientId, function(err, toke
nResponse) {

// Function returns error object in tokenResponse


// Invalid Username will return empty tokenResponse,
thus err is used
if (err) {
reject(tokenResponse == null ? err : tokenRespons
e);
}
resolve(tokenResponse);
})
}
);

// Check for ServicePrincipal Authentication


} else if (config.authenticationMode.toLowerCase() === "serviceprinci
pal") {
authorityUrl = authorityUrl.replace("common", config.tenantId);
let context = new AuthenticationContext(authorityUrl);
return new Promise(
(resolve, reject) => {
context.acquireTokenWithClientCredentials(config.scope, c
onfig.clientId, config.clientSecret, function(err, tokenResponse) {

// Function returns error object in tokenResponse


// Invalid Username will return empty tokenResponse,
thus err is used
if (err) {
reject(tokenResponse == null ? err : tokenRespons
e);
}
resolve(tokenResponse);
})
}
);
}
}

{
"authenticationMode": "MasterUser",
"authorityUri": "https://login.microsoftonline.com/common/",
"scope": "https://analysis.windows.net/powerbi/api",
"apiUrl": "https://api.powerbi.com/",
"clientId": "el identificador de nuestra app de AAD”,
"workspaceId": "id workspace donde tenemos el contenido a embeber",
"reportId": "id report que queremos embeber",
"pbiUsername": "cuenta del tenant con licencia PowerBI PRO y acceso
al workspace",
"pbiPassword": "Password de esa cuenta que hará de proxy",
"clientSecret": "id secreto de la app AAD",
"tenantId": "id del tenant de AAD"
}
Esquema de uso PBIE para organización

Paso a producción

3. Código
authenticate(): void {
const thisObj = this;

const msalConfig = {
auth: {
clientId: config.clientId
}
};

const loginRequest = {
scopes: config.scopes
};

const msalInstance: UserAgentApplication = new UserAgentApplicati


on(msalConfig);

function successCallback(response: AuthResponse): void {


let respuestaJSON = JSON.stringify(response)
if (response.tokenType === "id_token") {
thisObj.authenticate();

} else if (response.tokenType === "access_token") {

accessToken = response.accessToken;
thisObj.setUsername(response.account.name);
thisObj.getembedUrl();

} else {

thisObj.setState({ error: [("Token type is: " + response.


tokenType)] });
}
}

function failCallBack(error: AuthError): void {

thisObj.setState({ error: ["Redirect error: " + error] });


}

msalInstance.handleRedirectCallback(successCallback, failCallBack
);
// check if there is a cached user
if (msalInstance.getAccount()) {

// get access token silently from cached id-token


msalInstance.acquireTokenSilent(loginRequest)
.then((response: AuthResponse) => {

// get access token from response: response.accessTok


en
accessToken = response.accessToken;
this.setUsername(response.account.name);
this.getembedUrl();
})
.catch((err: AuthError) => {

// refresh access token silently from cached id-token


// makes the call to handleredirectcallback
if (err.name === "InteractionRequiredAuthError") {
msalInstance.acquireTokenRedirect(loginRequest);
}
else {
thisObj.setState({ error: [err.toString()] })
}
});
} else {

// user is not logged in or cached, you will need to log them


in to acquire a token
msalInstance.loginRedirect(loginRequest);
}
}
export const scopes: string[] = ["https://analysis.windows.net/powerbi/ap
i/Report.Read.All"];

// Client Id (Application Id) of the AAD app.


export const clientId: string = "…";

// Id of the workspace where the report is hosted


export const workspaceId: string = "…";

// Id of the report to be embedded


export const reportId: string = "…";

1. Flujo de información
2. Petición del cliente

3. Servicio Express

let models = window["powerbi-client"].models;


let reportContainer = $("#report-container").get(0);

// Initialize iframe for embedding report


powerbi.bootstrap(reportContainer, { type: "report" });

$.ajax({
type: "GET",
url: "/getEmbedToken",
dataType: "json",
data:{"report":"area"},
success: function(embedData) {

// Create a config object with type of the object, Embed details


and Token Type
let reportLoadConfig = {
type: "report",
tokenType: models.TokenType.Embed,
accessToken: embedData.accessToken,
embedUrl: embedData.embedUrl,
/*
// Enable this setting to remove gray shoulders from embedded
report
settings: {
background: models.BackgroundType.Transparent
}
*/
};

// Use the token expiry to regenerate Embed token for seamless en


d user experience
// Refer https://aka.ms/RefreshEmbedToken
tokenExpiry = embedData.expiry;

// Embed Power BI report when Access token and Embed URL are avai
lable
let report = powerbi.embed(reportContainer, reportLoadConfig);

app.get('/getEmbedToken', async function(req, res) {


// Get the details like Embed URL, Access token and Expiry
let result = await embedToken.generateEmbedToken(req.query.report);

// result.status specified the statusCode that will be sent along wit


h the result object
res.status(result.status).send(result);
});

You might also like