简体   繁体   中英

ASP.Net Core: X-Frame-Options strange behavior

I need to remove X-Frame-Options: SAMEORIGIN header from some of my actions which should render a content for an iframe. As long as it is added to requests by default I disabled it in Startup.cs : services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = false); . Then I wrote a simple middleware:

    app.Use(async (context, next) =>
    {
        context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");

        await next();
    });

Actions needed to answer to cross-domain requests are decorated with result filter attribute:

    public class SuppresXFrameOptionFilter : ResultFilterAttribute
    {
        public override async Task OnResultExecutionAsync(ResultExecutingContext context,
ResultExecutionDelegate next)
        {
            context.HttpContext.Response.Headers.Remove("X-Frame-Options");

            await next();
        }
    }

Here comes the weiredness. First cross-domain request fails because despite the filter works as expected in the end the X-Frame-Options: SAMEORIGIN is still present in the response (I checked it after next() in the middleware - the header reappeared). If I press F5 the header is no longer in the response and everything works as it should. That happens only with X-Frame-Options header, a custom one is removed correctly. What makes the X-Frame-Options which has been removed appear in a response again?

I would say on the first request Antiforgery saves the cookie which means it also tries to set the X-Frame-Options header.

If you want to disable that header in Antiforgery and manually handle it yourself, what you want is setting SuppressXFrameOptionsHeader to be true ;)

services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = true);

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