我需要使用服务主体或 AD 应用程序为 Power Bi 报告生成嵌入访问令牌。 我只想使用我的 AD 用户名和密码。
我正在分享两个示例代码。
Python:
import requests
# Constants
username = 'YOUR_POWER_BI_USERNAME' # Power BI username
password = 'YOUR_POWER_BI_PASSWORD' # Power BI password
workspace_id = 'YOUR_WORKSPACE_ID' # Power BI workspace ID
report_id = 'YOUR_REPORT_ID' # Power BI report ID
# Authenticate and get access token (user credentials)
def get_access_token():
auth_url = 'https://login.microsoftonline.com/common/oauth2/token'
auth_data = {
'grant_type': 'password',
'client_id': 'YOUR_CLIENT_ID',
'client_secret': 'YOUR_CLIENT_SECRET',
'resource': 'https://analysis.windows.net/powerbi/api',
'username': username,
'password': password,
'scope': 'https://analysis.windows.net/powerbi/api/.default'
}
response = requests.post(auth_url, data=auth_data)
response.raise_for_status()
return response.json()['access_token']
# Generate Embed Token
def generate_embed_token(access_token):
embed_url = f'https://api.powerbi.com/v1.0/myorg/groups/{workspace_id}/reports/{report_id}/GenerateToken'
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
body = {
'accessLevel': 'View'
}
response = requests.post(embed_url, headers=headers, json=body)
response.raise_for_status()
return response.json()
# Get Embed Token
access_token = get_access_token()
embed_token_data = generate_embed_token(access_token)
print(f"Embed Token: {embed_token_data['token']}")
print(f"Embed URL: {embed_token_data['embedUrl']}")
Java 脚本
npm install axios
const axios = require('axios');
const qs = require('qs');
// Constants
const username = 'YOUR_POWER_BI_USERNAME'; // Power BI username
const password = 'YOUR_POWER_BI_PASSWORD'; // Power BI password
const workspaceId = 'YOUR_WORKSPACE_ID'; // Power BI workspace ID
const reportId = 'YOUR_REPORT_ID'; // Power BI report ID
// Function to get access token
async function getAccessToken() {
const authUrl = 'https://login.microsoftonline.com/common/oauth2/token';
const authData = {
grant_type: 'password',
client_id: 'YOUR_CLIENT_ID',
client_secret: 'YOUR_CLIENT_SECRET',
resource: 'https://analysis.windows.net/powerbi/api',
username: username,
password: password,
scope: 'https://analysis.windows.net/powerbi/api/.default'
};
try {
const response = await axios.post(authUrl, qs.stringify(authData), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
return response.data.access_token;
} catch (error) {
console.error('Error getting access token:', error);
throw error;
}
}
// Function to generate embed token
async function generateEmbedToken(accessToken) {
const embedUrl = `https://api.powerbi.com/v1.0/myorg/groups/${workspaceId}/reports/${reportId}/GenerateToken`;
const body = {
accessLevel: 'View'
};
try {
const response = await axios.post(embedUrl, body, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
});
return response.data;
} catch (error) {
console.error('Error generating embed token:', error);
throw error;
}
}
// Main function
async function embedReport() {
try {
const accessToken = await getAccessToken();
const embedTokenData = await generateEmbedToken(accessToken);
console.log(`Embed Token: ${embedTokenData.token}`);
console.log(`Embed URL: ${embedTokenData.embedUrl}`);
} catch (error) {
console.error('Error embedding report:', error);
}
}
// Run the function
embedReport();
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/powerbi.js"></script>
</head>
<body>
<div id="reportContainer" style="height: 600px;"></div>
<script>
// Replace with actual embed token and embed URL
const embedToken = 'YOUR_EMBED_TOKEN';
const embedUrl = 'YOUR_EMBED_URL';
// Configuration
const config = {
type: 'report',
tokenType: powerbi.models.TokenType.Embed,
accessToken: embedToken,
embedUrl: embedUrl,
id: 'YOUR_REPORT_ID',
settings: {
filterPaneEnabled: true,
navContentPaneEnabled: true
}
};
// Embed the report
const reportContainer = document.getElementById('reportContainer');
powerbi.embed(reportContainer, config);
</script>
</body>
</html>