We are working on a web project (ASP.NET Core 3.1). We have a requirement to allow to open only a specific page in an iframe from other origins. All other pages should not be accessible through iFrame.
We have tried a few ways as below:
- We have tried to remove
X-Frame-Options: SAMEORIGIN
from the header using middleware.
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);
}
But, didn't get server headers (X-Frame-Options) here in middleware.
- We have used content security policy
<add name="Content-Security-Policy" value="frame-ancestors 'self' *.website.com" />
This works for the specified origin, however, it allows all the pages to be loaded in iframe.
- We have tried to remove
X-Frame-Options
header from theweb.config
file
<add name="X-Frame-Options" value="SAMEORIGIN" />
- We have tried to suppress
X-Frame-Options
header, but it allowed all the domains
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;
});
}
So, the question is, how we can allow only a specific page in an iframe from other domains?
EDIT
I have already enabled the CORS.
<add name="Access-Control-Allow-Origin" value="*" />
CodePudding user response:
You can use the [EnableCors]
attribute only for the specific controller method instead of applying it globally: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api#scope-rules-for-enablecors
CodePudding user response:
We have tried several different ways and come up with a solution.
First, need to remove <add name="X-Frame-Options" value="SAMEORIGIN" />
from web config file.
Second, add X-Frame-Options
programmatically for all the requests expect page that needs to open in iFrame.
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();
});
});