简体   繁体   中英

How to allow specific page in an iFrame - ASP.NET Core

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 cross domains. All other pages should not be accessible through iFrame.

We have tried a few ways as below:

  1. 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.

  1. We have used content security policy
<add name="Content-Security-Policy" value="frame-ancestors 'self' *.website.com" />

This works for the specified domain, however, it allows all the pages to be loaded in iframe.

  1. We have tried to remove X-Frame-Options header from the web.config file
<add name="X-Frame-Options" value="SAMEORIGIN" />
  1. 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 single page/specific page in an iframe from cross domains?

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

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();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM