如何在 Rails 4 中覆盖控制器或动作的 X-Frame-Options [英] How to override X-Frame-Options for a controller or action in Rails 4

查看:15
本文介绍了如何在 Rails 4 中覆盖控制器或动作的 X-Frame-Options的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 4 似乎为 X-Frame-Options HTTP 响应标头设置了默认值 SAMEORIGIN.这对于安全来说很棒,但它不允许您的应用程序的某些部分在不同域的 iframe 中可用.

Rails 4 appears to set a default value of SAMEORIGIN for the X-Frame-Options HTTP response header. This is great for security, but it does not allow for parts of your app to be available in an iframe on a different domain.

您可以使用 config.action_dispatch.default_headers 设置全局覆盖 X-Frame-Options 的值:

You can override the value of X-Frame-Options globally using the config.action_dispatch.default_headers setting:

config.action_dispatch.default_headers['X-Frame-Options'] = "ALLOW-FROM https://apps.facebook.com"

但是您如何仅针对单个控制器或操作覆盖它?

But how do you override it for just a single controller or action?

推荐答案

如果你想完全删除标题,你可以创建一个 after_action 过滤器:

If you want to remove the header completely, you can create an after_action filter:

class FilesController < ApplicationController
  after_action :allow_iframe, only: :embed

  def embed
  end

private

  def allow_iframe
    response.headers.except! 'X-Frame-Options'
  end
end

或者,当然,您可以对 after_action 进行编码以将值设置为不同的值:

Or, of course, you can code the after_action to set the value to something different:

class FacebookController < ApplicationController
  after_action :allow_facebook_iframe

private

  def allow_facebook_iframe
    response.headers['X-Frame-Options'] = 'ALLOW-FROM https://apps.facebook.com'
  end
end

请注意,在调试时,您需要清除某些浏览器(我是 Chrome)中的缓存.

Note that you need to clear your cache in certain browsers (Chrome for me) while debugging this.

这篇关于如何在 Rails 4 中覆盖控制器或动作的 X-Frame-Options的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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