Rails 使用iframe报错:IFRAME: Refused to display document because display forbidden by X-Frame-Options

本文介绍如何在Rails应用中设置X-Frame-Options来增强安全性,包括在layout文件中添加元标签及在控制器中设置HTTP头。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:在layout目录下的application.html.erb文件中添加:
<meta http-equiv="X-Frame-Options" content="GOFORIT">
例如:
<!DOCTYPE html>
<html>
<head>
  <title>电子病历系统</title>
  <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
  <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
  <meta http-equiv="X-Frame-Options" content="GOFORIT">
  <%= csrf_meta_tags %>
</head>
<body>

<%= yield %>

</body>
</html>

第二步:在controllers目录下的application_controller.rb添加:

 protect_from_forgery with: :exception
  before_filter :add_xframe
  def add_xframe
    headers['X-Frame-Options'] = 'GOFORIT'
  end

例如:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_filter :add_xframe
  def add_xframe
    headers['X-Frame-Options'] = 'GOFORIT'
  end
end

这样浏览器会报如下警告信息:

'Invalid 'X-Frame-Options' header encountered when loading....GOFORIT' is not a recognized directive. The header will be ignored.

即把‘GOFORIT’换成‘ALLOWALL’就ok了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值