[英]How to allow specific page in an iFrame - ASP.NET Core
我们正在开发一个 web 项目(ASP.NET Core 3.1)。 我们要求只允许从跨域打开 iframe 中的特定页面。 不应通过 iFrame 访问所有其他页面。
我们尝试了以下几种方法:
X-Frame-Options: SAMEORIGIN
。public async Task Invoke(HttpContext context)
{
context.Response.OnStarting((state) =>
{
_headersToRemove.ForEach(header =>
{
if (context.Response.Headers.ContainsKey(header))
{
context.Response.Headers.Remove(header);
}
});
return Task.FromResult(0);
}, null);
await next.Invoke(context);
}
但是,在中间件中没有得到服务器标头(X-Frame-Options)。
<add name="Content-Security-Policy" value="frame-ancestors 'self' *.website.com" />
这适用于指定的域,但是,它允许在 iframe 中加载所有页面。
web.config
文件中删除X-Frame-Options
header<add name="X-Frame-Options" value="SAMEORIGIN" />
X-Frame-Options
header,但它允许所有域public static void AddAntiForgery(this IServiceCollection services)
{
services.AddAntiforgery(options =>
{
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.Cookie.HttpOnly = true;
options.Cookie.Name = "_app";
options.Cookie.SameSite = SameSiteMode.Strict;
options.SuppressXFrameOptionsHeader = true;
});
}
所以,问题是,我们如何才能只允许跨域的 iframe 中的单个页面/特定页面?
您只能将[EnableCors]
属性用于特定的 controller 方法,而不是全局应用它: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-请求-in-web-api#scope-rules-for-enablecors
我们尝试了几种不同的方法并提出了解决方案。
首先,需要从 web 配置文件中删除<add name="X-Frame-Options" value="SAMEORIGIN" />
。
其次,以编程方式为所有需要在 iFrame 中打开的请求页面添加X-Frame-Options
。
app.UseWhen(context => !context.Request.Path.StartsWithSegments("/controller/action"), appBuilder =>
{
appBuilder.Use(async (context, next) =>
{
context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
await next();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.