简体   繁体   English

ASP.Net Core:X-Frame-Options奇怪的行为

[英]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. 我需要从一些应为iframe呈现内容的操作中删除X-Frame-Options: SAMEORIGIN标头。 As long as it is added to requests by default I disabled it in Startup.cs : services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = false); 只要默认情况下将其添加到请求中,我就在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). 第一个跨域请求失败,因为尽管过滤器最终运行正常,但X-Frame-Options: SAMEORIGIN仍然存在于响应中(我在中间件中的next()之后检查了它-重新出现了标头)。 If I press F5 the header is no longer in the response and everything works as it should. 如果我按F5键,标题将不再在响应中,并且一切正常。 That happens only with X-Frame-Options header, a custom one is removed correctly. 只有使用X-Frame-Options标头会发生这种情况,正确删除了一个自定义标头。 What makes the X-Frame-Options which has been removed appear in a response again? 是什么使被删除的X-Frame-Options再次出现在响应中?

I would say on the first request Antiforgery saves the cookie which means it also tries to set the X-Frame-Options header. 我会说在第一个请求上, Antiforgery保存了cookie,这意味着它也试图设置X-Frame-Options标头。

If you want to disable that header in Antiforgery and manually handle it yourself, what you want is setting SuppressXFrameOptionsHeader to be true ;) 如果要在Antiforgery中禁用该标头并自己手动处理,则需要将SuppressXFrameOptionsHeader设置为true ;)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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