LoginSignup
2
2

More than 3 years have passed since last update.

【Content-Security-Policy】インラインスクリプトを読み込む

Posted at

Content-Security-Policy

header("Content-Security-Policy: default-src 'self';");

  • クロスサイトスクリプティング(XSS)攻撃に対する耐性を高めるためのセキュリティ機能
  • js, css, 画像などをサイト自身のオリジンのみから読み込む
  • インラインスクリプトやインラインスタイルも読み込まない。
<html>
    <head>
        <meta charaset="UTF-8">
        <title>インラインスクリプト</title>
    </head>
    <body>
        < script>
            alert("hello world");
        </script>
    </body>
</html>

インラインスクリプトを許可したい

ナンスを使用するには、script タグに nonce 属性を指定します。この値は、信頼できる参照元リストに含まれる値と一致する必要があります。

続いて、nonce- キーワードに付加したナンスを、script-src ディレクティブに追加します。

<?php
$token = Token::get(); // ワンタイムトークンを生成
header("Content-Security-Policy: script-src 'nonce-{$token}';");
?>

<script nonce="<?=$token?>">
    alert("hollo world");
</script>

インラインスタイルなども同じ方法で読み込める。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2