[英]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.