ASP.Net Core:X-Frame-Options奇怪的行为 [英] ASP.Net Core: X-Frame-Options strange behavior

查看:1342
本文介绍了ASP.Net Core:X-Frame-Options奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从一些应为iframe呈现内容的操作中删除X-Frame-Options: SAMEORIGIN标头.只要默认情况下将其添加到请求中,我就会在Startup.cs:services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = false);中将其禁用.然后我写了一个简单的中间件:

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

奇怪的来了.第一个跨域请求失败,因为尽管过滤器最终运行正常,但响应中仍然存在X-Frame-Options: SAMEORIGIN(我在中间件中的next()之后检查了它-重新出现了标头).如果我按F5键,标题将不再在响应中,并且一切正常.仅使用X-Frame-Options标头会发生这种情况,正确删除了一个自定义标头. 是什么使被删除的X-Frame-Options再次出现在响应中?

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.

如果您想在Antiforgery中禁用该标头并自己手动处理,则需要将SuppressXFrameOptionsHeader 设置为true ;)

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

这篇关于ASP.Net Core:X-Frame-Options奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆