如何解决iframe静默刷新令牌时的X-Frame-Options: deny问题?
问题描述
我的应用通过静默刷新机制续订令牌,该机制会加载指向Identity Server端点的iframe。但iframe尝试加载https://localhost:9443/时,浏览器控制台报错:
Refused to display 'https://localhost:9443/' in a frame because it set 'X-Frame-Options' to 'deny'.
环境配置
- Identity Server: WSO2 IS 7.0.0,运行地址
https://localhost:9443/ - 前端框架: Angular 18,使用
angular-oauth2-oidc包实现认证 - 静默刷新: 使用库内置的
silentRefresh()方法
认证配置代码
export const authConfig: AuthConfig = { issuer: 'https://localhost:9443/oauth2/token', redirectUri: window.location.origin, clientId: '6wgRGIKSFcB61WSDSsf0n1fysGIa', dummyClientSecret : "fNksWZHkxXQMv14GZ9oVYJaYyOrEJchcFuPsurYxGloa", strictDiscoveryDocumentValidation: false, responseType: 'code', scope: 'openid profile roles', showDebugInformation: true, silentRefreshRedirectUri: window.location.origin + '/silent-refresh.html', useSilentRefresh: true, sessionChecksEnabled: true, timeoutFactor: 0.75, clearHashAfterLogin: true, logoutUrl: 'https://localhost:9443/oidc/logout', skipIssuerCheck: true, };
silent-refresh.html代码
<html> <body> <script> parent.postMessage(location.hash, location.origin); </script> </body> </html>
静默刷新调用代码
this .oauthService .silentRefresh() .then(info => console.debug('refresh ok', info)) .catch(err => console.error('refresh error', err));
解决方案
1. 调整WSO2 IS的X-Frame-Options配置
WSO2 IS默认设置X-Frame-Options: deny,禁止自身被嵌入iframe。要让前端能通过iframe加载其端点,需修改配置:
- 打开WSO2 IS安装目录下的
repository/conf/deployment.toml文件 - 添加或更新以下配置,将
http://localhost:4200替换为你的前端实际域名(本地开发通常用这个地址):
若为开发环境临时放宽限制(生产环境不建议),可设置为:[http.headers] x_frame_options = "ALLOW-FROM http://localhost:4200"[http.headers] x_frame_options = "SAMEORIGIN" - 修改完成后重启WSO2 IS服务使配置生效
2. 修正认证配置中的Issuer地址
当前authConfig里的issuer指向令牌端点/oauth2/token,这不符合OIDC规范。正确的OIDC发现端点应为https://localhost:9443/oauth2/oidcdiscovery,修改后库会自动识别正确的静默刷新端点,避免错误加载根路径:
issuer: 'https://localhost:9443/oauth2/oidcdiscovery',
3. 完善重定向URI与CORS配置
- 登录WSO2 IS控制台,找到对应客户端ID为
6wgRGIKSFcB61WSDSsf0n1fysGIa的服务提供者 - 将前端的
silentRefreshRedirectUri(例如http://localhost:4200/silent-refresh.html)添加到授权重定向URI列表中 - 同时在
deployment.toml中配置CORS允许前端域名:[cors] allow_origins = ["http://localhost:4200"] allow_methods = ["GET", "POST", "OPTIONS"] allow_headers = ["Authorization", "Content-Type"] expose_headers = ["Authorization"] supports_credentials = true
4. 验证静默刷新流程
重启WSO2 IS和前端项目,调用silentRefresh()方法,检查控制台是否仍有报错。若问题存在,可借助showDebugInformation: true的调试输出,确认请求端点是否正确,排查具体环节。
内容的提问来源于stack exchange,提问作者ayoubmrk
相关产品推荐
相关产品推荐

