将PowerBI集成到Angular应用时出现CSP错误
在Angular应用中嵌入PowerBI报表时遭遇CSP错误
问题详情
将PowerBI报表嵌入Angular应用时出现内容安全策略(CSP)错误,错误提示内容安全策略阻止了相关资源加载,涉及脚本、样式等资源的访问限制。
已尝试的嵌入代码
const accessToken = "token" const orginalUrl ="url" const embedReportId = "id"; const config = { type: 'report', id: embedReportId, embedUrl: orginalUrl, tokenType: pbi.models.TokenType.Aad, accessToken: accessToken }; let reportContainer = this.reportContainer.nativeElement; let powerbi = new pbi.service.Service( pbi.factories.hpmFactory, pbi.factories.wpmpFactory, pbi.factories.routerFactory ); let report = powerbi.embed(reportContainer, config); report.off('loaded'); report.on('loaded', () => { console.log('Loaded'); }); report.on('error', (er: any) => { console.log('Error', er); });
解决办法
- 添加CSP Meta标签
在项目根目录的index.html文件<head>中插入以下meta标签,放行PowerBI所需的资源域名:
<meta http-equiv="Content-Security-Policy" content=" default-src 'self'; script-src 'self' https://*.powerbi.com https://*.powerbi.com.cn; style-src 'self' 'unsafe-inline' https://*.powerbi.com https://*.powerbi.com.cn; img-src 'self' data: https://*.powerbi.com https://*.powerbi.com.cn; font-src 'self' https://*.powerbi.com https://*.powerbi.com.cn; frame-src https://*.powerbi.com https://*.powerbi.com.cn; ">
注:'unsafe-inline'用于兼容PowerBI的内联样式与脚本,若需严格合规,后续可替换为nonce或hash方案。
- Angular CLI构建配置
如果使用Angular CLI构建项目,可直接在angular.json的build.options中配置CSP规则:
"build": { "options": { "contentSecurityPolicy": "default-src 'self'; script-src 'self' https://*.powerbi.com; style-src 'self' 'unsafe-inline' https://*.powerbi.com; img-src 'self' data: https://*.powerbi.com; font-src 'self' https://*.powerbi.com; frame-src https://*.powerbi.com;" } }
- 基础校验项
- 确认
accessToken拥有目标报表的嵌入权限 - 检查
embedUrl为PowerBI官方提供的正确嵌入地址(格式示例:https://app.powerbi.com/reportEmbed?reportId=xxx&groupId=xxx) - 确保
index.html已引入PowerBI嵌入脚本:<script src="https://microsoft.github.io/PowerBI-JavaScript/dist/powerbi.min.js"></script>
内容的提问来源于stack exchange,提问作者anandu S Kumar
相关产品推荐
相关产品推荐

