Content-Security-Policy: form-action 指令

Baseline 已廣泛支援

該特性已非常成熟,可在多種裝置和瀏覽器版本上使用。自 2017 年 4 月以來,它已在各大瀏覽器上可用。

HTTP Content-Security-Policy (CSP) 的 form-action 指令限制了給定上下文中表單提交的目標 URL。

警告: form-action 是否應阻止表單提交後的重定向存在爭議,並且瀏覽器在此方面的實現不一致(例如,Firefox 57 不阻止重定向,而 Chrome 63 阻止)。

CSP 版本 2
指令型別 導航指令
default-src 回退 否。不設定此項則允許任何內容。

語法

http
Content-Security-Policy: form-action 'none';
Content-Security-Policy: form-action <source-expression-list>;

此指令可以具有以下值之一

'none'

不允許進行任何表單提交。單引號是強制性的。

<source-expression-list>

以空格分隔的源表示式值列表。表單提交可以傳送到與任何給定源表示式匹配的 URL。對於此指令,以下源表示式值適用

示例

Meta 標籤配置

html
<meta http-equiv="Content-Security-Policy" content="form-action 'none'" />

Apache 配置

apacheconf
<IfModule mod_headers.c>
  Header set Content-Security-Policy "form-action 'none';"
</IfModule>

Nginx 配置

nginx
add_header Content-Security-Policy "form-action 'none';"

違規案例

使用將 action 設定為內聯 JavaScript 的 <form> 元素將導致 CSP 違規。

html
<meta http-equiv="Content-Security-Policy" content="form-action 'none'" />

<form action="javascript:alert('Foo')" id="form1" method="post">
  <input type="text" name="fieldName" value="fieldValue" />
  <input type="submit" id="submit" value="submit" />
</form>

<!--
// Error: Refused to send form data because it violates the following
// Content Security Policy directive: "form-action 'none'".
-->

規範

規範
內容安全策略級別 3
# directive-form-action

瀏覽器相容性

另見