Figma Embed API返回401 Unauthorized的原因排查求助
Figma Embed API集成Angular应用时的401授权错误问题
问题描述
我正在尝试将Figma原型集成到Angular应用中,需通过Figma Embed API追踪用户路径、点击等数据。已完成以下配置:
- 在Figma账户创建OAuth应用,设置的允许源(应用部署于localhost:4200)包括:
- https://localhost
- https://localhost:4200
- http://localhost:4200
- http://localhost
- iframe代码中已附加OAuth应用的客户端ID
- Figma文件和原型共享链接设为「任何拥有链接的人可查看」
但控制台持续抛出401错误,且完全无法接收Embed API的消息:
Uncaught (in promise) v: XHR for "/api/user/state" failed with status 401
401 Unauthorized for GET: https://www.figma.com/api/user/state?redact=org_billing_data&team_id=[teamID]
401 Unauthorised for GET: https://www.figma.com/api/user/state?team_id=[teamID]&omit_core_data=1&file_key=[fileKey]
嵌入代码
HTML部分
<iframe id="my-frame" #myFrame [height]="iFrameHeight" [width]="iFrameWidth" [src]='figmaEmbedUrl' allowfullscreen ></iframe>
Angular组件代码
constructor( private sanitizer: DomSanitizer, private figmaService: FigmaService, ) { this.setUrlParams(); const rawUrl = this.constructUrl(); this.figmaEmbedUrl = this.sanitizer.bypassSecurityTrustResourceUrl(rawUrl); console.log("Figma url: ", this.figmaEmbedUrl); } setUrlParams() { this.urlParams = `${this.startPageId !== '' ? 'page-id=' + this.startPageId + '&' : ''}node-id=${this.startNodeId}&embed-host=share&footer=${this.showFooter}&viewport-controls=${this.showViewportControls}&show-proto-sidebar=${this.showSidebar}&hotspot-hints=${this.showHotspotHints}&device-frame=${this.showDeviceFrame}&scaling=${this.scaling}&content-scaling=${this.contentScaling}`; console.log("URL params: ", this.urlParams); } constructUrl() { return `https://embed.figma.com/${this.linkType}/${this.fileKey}/${this.projectName}?${this.urlParams}&client-id=${this.clientId}`; }
解决方案
1. 精简允许源配置
保留与Angular应用实际运行地址完全匹配的条目即可,比如只留http://localhost:4200(如果用HTTP运行)或https://localhost:4200(如果启用HTTPS),冗余的不带端口条目可能导致匹配异常。
2. 校验Embed URL构造逻辑
- 确认
linkType值为proto(原型嵌入专用,而非file) - 检查
client-id参数是否正确附加在URL末尾,客户端ID无拼写错误 - 核对
fileKey和projectName的正确性,可直接从Figma原型的共享链接中提取对应值
3. 调整Angular安全策略
- 确保Angular的CSP(内容安全策略)允许加载Figma嵌入资源,可在
index.html中临时添加测试:<meta http-equiv="Content-Security-Policy" content="frame-src https://embed.figma.com;"> - 确认
bypassSecurityTrustResourceUrl处理后的URL未被Angular安全机制篡改
4. 确认文件及团队权限
- 除了文件的「任何拥有链接的人可查看」设置,还要检查文件所属团队是否限制外部嵌入权限
- 若文件在团队空间内,需确保团队设置中允许外部应用访问
5. 完善消息监听逻辑
添加正确的跨域消息监听代码,确保能接收Figma Embed API的回调:
ngAfterViewInit() { window.addEventListener('message', (event) => { if (event.origin === 'https://embed.figma.com') { console.log('Figma API消息:', event.data); // 在此处理用户路径、点击等数据 } }); }
6. 排除OAuth配置问题
先移除URL中的client-id参数,测试基础嵌入是否正常。若基础嵌入可用,再重新检查OAuth应用的启用状态、客户端ID正确性。
内容的提问来源于stack exchange,提问作者Stefan van Beek
相关产品推荐
相关产品推荐

