コンテンツへスキップ
アプリケーションの構築設定コンテンツセキュリティポリシー

コンテンツセキュリティポリシー

コンテンツセキュリティポリシー (CSP) は、クロスサイトスクリプティング (XSS)、クリックジャッキング、その他のコードインジェクション攻撃などのさまざまなセキュリティ上の脅威から Next.js アプリケーションを保護するために重要です。

CSP を使用することで、開発者は、コンテンツソース、スクリプト、スタイルシート、画像、フォント、オブジェクト、メディア (オーディオ、ビデオ)、iframe などに対して許可されるオリジンを指定できます。

ノンス

ノンス は、1 回限りの使用のために作成された、ユニークなランダムな文字列です。これは、厳格な CSP ディレクティブを回避して、特定のインラインスクリプトやスタイルを Selective に実行できるようにするために、CSP と組み合わせて使用されます。

なぜノンスを使用するのか?

CSP は悪意のあるスクリプトをブロックするように設計されていますが、インラインスクリプトが必要な正当なシナリオがあります。このような場合、ノンスは、正しいノンスを持っている場合にこれらのスクリプトの実行を許可する方法を提供します。

ミドルウェアでノンスを追加する

ミドルウェア を使用すると、ページのレンダリング前にヘッダーを追加し、ノンスを生成できます。

ページが表示されるたびに、新しいノンスを生成する必要があります。つまり、ノンスを追加するには、**動的レンダリングを使用する必要**があります。

例:

middleware.ts
import { NextRequest, NextResponse } from 'next/server'
 
export function middleware(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
  const cspHeader = `
    default-src 'self';
    script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
    style-src 'self' 'nonce-${nonce}';
    img-src 'self' blob: data:;
    font-src 'self';
    object-src 'none';
    base-uri 'self';
    form-action 'self';
    frame-ancestors 'none';
    upgrade-insecure-requests;
`
  // Replace newline characters and spaces
  const contentSecurityPolicyHeaderValue = cspHeader
    .replace(/\s{2,}/g, ' ')
    .trim()
 
  const requestHeaders = new Headers(request.headers)
  requestHeaders.set('x-nonce', nonce)
 
  requestHeaders.set(
    'Content-Security-Policy',
    contentSecurityPolicyHeaderValue
  )
 
  const response = NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  })
  response.headers.set(
    'Content-Security-Policy',
    contentSecurityPolicyHeaderValue
  )
 
  return response
}

デフォルトでは、ミドルウェアはすべてのリクエストで実行されます。matcher を使用して、特定のパスで実行するようにミドルウェアをフィルタリングできます。

CSP ヘッダーを必要としないプリフェッチ (next/link から) および静的アセットのマッチングを無視することをお勧めします。

middleware.ts
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    {
      source: '/((?!api|_next/static|_next/image|favicon.ico).*)',
      missing: [
        { type: 'header', key: 'next-router-prefetch' },
        { type: 'header', key: 'purpose', value: 'prefetch' },
      ],
    },
  ],
}

ノンスを読む

headers を使用して、サーバーコンポーネントから nonce を読み取ることができるようになりました。

app/page.tsx
import { headers } from 'next/headers'
import Script from 'next/script'
 
export default async function Page() {
  const nonce = (await headers()).get('x-nonce')
 
  return (
    <Script
      src="https://#/gtag/js"
      strategy="afterInteractive"
      nonce={nonce}
    />
  )
}

Nonce なし

nonce を必要としないアプリケーションの場合、next.config.js ファイルで CSP ヘッダーを直接設定できます。

next.config.js
const cspHeader = `
    default-src 'self';
    script-src 'self' 'unsafe-eval' 'unsafe-inline';
    style-src 'self' 'unsafe-inline';
    img-src 'self' blob: data:;
    font-src 'self';
    object-src 'none';
    base-uri 'self';
    form-action 'self';
    frame-ancestors 'none';
    upgrade-insecure-requests;
`
 
module.exports = {
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: [
          {
            key: 'Content-Security-Policy',
            value: cspHeader.replace(/\n/g, ''),
          },
        ],
      },
    ]
  },
}

バージョン履歴

nonce を適切に処理および適用するには、Next.js の v13.4.20+ を使用することをお勧めします。