Cross-Origin Resource Sharing (CORS)

QuarkusでCORSを有効にして設定し、許可されるオリジン、メソッド、ヘッダーを指定することで、ブラウザがクロスオリジンリクエストを安全に処理できるようになります。

Cross-Origin Resource Sharing (CORS) は、HTTP ヘッダーを使用して、外部オリジンからのリソースに対するブラウザーリクエストを安全に管理します。 許可されたオリジン、メソッド、ヘッダーを指定して、Quarkus サーバーは CORS フィルターを使用して、制御されたアクセスを維持しながらブラウザーがドメイン間でリソースを要求できるようします。 このメカニズムにより、セキュリティーが強化され、正当なクロスオリジンリクエストがサポートされます。 オリジン定義の詳細は、 Web Origin Concept を参照してください。

CORS フィルターの有効化

アプリケーションで CORS ポリシーを適用するには、src/main/resources/application.properties ファイルに次の行を追加して、Quarkus CORS フィルターを有効にします。

quarkus.http.cors.enabled=true

フィルターは、すべての受信 HTTP リクエストをインターセプトしてクロスオリジンリクエストを識別し、設定されたポリシーを適用します。 次に、フィルターは HTTP 応答に CORS ヘッダーを追加し、許可されたオリジンとアクセスパラメーターについてブラウザーに通知します。 プリフライトリクエストの場合、フィルターは HTTP 応答を直ちに返します。 通常の CORS リクエストの場合、リクエストが設定されたポリシーに違反すると、フィルターは HTTP 403 ステータスでアクセスを拒否します。それ以外の場合、ポリシーで許可されていれば、フィルターはリクエストを宛先に転送します。

その名前にもかかわらず、CORS フィルターは オリジン検証 に基づく CSRF 攻撃も防止できます。 したがって、ブラウザーはクロスオリジン JavaScript および HTML フォームリクエストに対して Origin ヘッダー を設定することが期待されるため、REST CSRF フィルター の代わりに CORS フィルターの使用を検討してもよいでしょう。

特に HTML フォームを使用する場合、アプリケーションにアクセスする際にブラウザーがクロスオリジンリクエストに対して Origin ヘッダーを設定することを確認してから、CORS フィルターを使用して オリジン検証 による CSRF を防止する必要があります。

詳細な設定オプションについては、次の設定プロパティーセクションを参照してください。

ビルド時に固定される設定プロパティ - それ以外の設定プロパティは実行時に上書き可能

Configuration property

タイプ

デフォルト

Enable the CORS filter.

Environment variable: QUARKUS_HTTP_CORS_ENABLED

Show more

boolean

false

The origins allowed for CORS.

A comma-separated list of valid URLs, such as http://www.quarkus.io,http://localhost:3000. URLs enclosed in forward slashes are interpreted as regular expressions.

Environment variable: QUARKUS_HTTP_CORS_ORIGINS

Show more

文字列のリスト

The HTTP methods allowed for CORS requests.

A comma-separated list of valid HTTP methods, such as GET,PUT,POST. If not set, the filter allows any HTTP method by default.

This property is not used to control same-origin HTTP request methods.

Default: Any HTTP request method is allowed.

Environment variable: QUARKUS_HTTP_CORS_METHODS

Show more

文字列のリスト

The HTTP headers allowed for CORS requests.

A comma-separated list of valid headers, such as X-Custom,Content-Disposition. If not set, the filter allows any header by default.

Default: Any HTTP request header is allowed.

Environment variable: QUARKUS_HTTP_CORS_HEADERS

Show more

文字列のリスト

The HTTP headers exposed in CORS responses.

A comma-separated list of headers to expose, such as X-Custom,Content-Disposition.

Default: No headers are exposed.

Environment variable: QUARKUS_HTTP_CORS_EXPOSED_HEADERS

Show more

文字列のリスト

The Access-Control-Max-Age response header value in java.time.Duration format.

Informs the browser how long it can cache the results of a preflight request.

Environment variable: QUARKUS_HTTP_CORS_ACCESS_CONTROL_MAX_AGE

Show more

Duration 

The Access-Control-Allow-Credentials response header.

Tells browsers if front-end JavaScript can be allowed to access credentials when the request’s credentials mode, Request.credentials, is set to include.

Default: true if the quarkus.http.cors.origins property is set and matches the precise Origin header value.

Environment variable: QUARKUS_HTTP_CORS_ACCESS_CONTROL_ALLOW_CREDENTIALS

Show more

boolean

Whether to return the exact request origin in the Access-Control-Allow-Origin response header.

When set to true (the default), the filter echoes back the request’s Origin header value. When set to false and origins is configured as *, the response will contain the literal Access-Control-Allow-Origin: * instead of echoing the request origin. This is useful for public APIs where HTTP caching is important, as echoing the origin requires Vary: Origin and defeats shared caches.

Note: When * is returned as the origin, Access-Control-Allow-Credentials is forced to false per the CORS specification.

Environment variable: QUARKUS_HTTP_CORS_RETURN_EXACT_ORIGINS

Show more

boolean

true

Whether to add the Vary: Origin response header to CORS responses when the origin is not a wildcard.

The Vary: Origin header tells HTTP caches that the response depends on the request’s Origin header, preventing a cached response for one origin from being served to a different origin.

This should remain enabled (the default) in most setups, especially when a reverse proxy or CDN may cache responses.

Environment variable: QUARKUS_HTTP_CORS_VARY_ORIGIN

Show more

boolean

true

期間フォーマットについて

期間の値を書くには、標準の java.time.Duration フォーマットを使います。 詳細は Duration#parse() Java API documentation を参照してください。

数字で始まる簡略化した書式を使うこともできます:

  • 数値のみの場合は、秒単位の時間を表します。

  • 数値の後に ms が続く場合は、ミリ秒単位の時間を表します。

その他の場合は、簡略化されたフォーマットが解析のために java.time.Duration フォーマットに変換されます:

  • 数値の後に h 、 m 、 s が続く場合は、その前に PT が付けられます。

  • 数値の後に d が続く場合は、その前に P が付けられます。

CORS 設定の例

次の例は、オリジンの 1 つを定義する正規表現など、完全な CORS フィルター設定を示しています。

quarkus.http.cors.enabled=true (1)
quarkus.http.cors.origins=http://example.com,http://www.example.io,/https://([a-z0-9\\-_]+)\\\\.app\\\\.mydomain\\\\.com/ (2)
quarkus.http.cors.methods=GET,PUT,POST (3)
quarkus.http.cors.headers=X-Custom (4)
quarkus.http.cors.exposed-headers=Content-Disposition (5)
quarkus.http.cors.access-control-max-age=24H (6)
quarkus.http.cors.access-control-allow-credentials=true (7)
1 CORS フィルターを有効にします。
2 正規表現を含む、許可されるオリジンを指定します。指定しない場合は CORS は許可されず、同一オリジンのリクエストのみが許可されます。
3 クロスオリジンリクエストに使用可能な HTTP メソッドを表示します。
4 クライアントがリクエストに含めることができるカスタムヘッダーを宣言します。
5 クライアントがアクセスできる応答ヘッダーを識別します。
6 プリフライトリクエストの結果をキャッシュする期間を設定します。
7 クロスオリジンリクエストで Cookie または認証情報を許可します。

application.properties ファイルで正規表現を使用する場合は、適切な動作を確保するために、特殊文字を 4 つのバックスラッシュ (\\\\) でエスケープします。 たとえば:

  • \\\\. はリテラルの . 文字として解釈されます。

  • \\. は、正規表現メタデータ文字として任意の 1 文字として解釈されます。

誤ってエスケープされたパターンは、意図しない動作やセキュリティーの脆弱性につながる可能性があります。 デプロイメントする前に必ず正規表現の構文を確認してください。

すべてのオリジンを受け入れる場合

本番環境で quarkus.http.cors.origins=* を使用して無制限のオリジンを許可すると、不正なデータアクセスやリソースの悪用など、重大なセキュリティーリスクが生じます。 本番環境では、quarkus.http.cors.origins プロパティーで明示的なオリジンを定義してください。

本番環境で全てのオリジンを受け入れることが適切となる唯一の例外は、Cookie の管理、リクエストデータのディスクへの保存、または同様の操作など、いかなる種類の副作用もない読み取り専用の公開 API アプリケーションの場合です。 このような場合、HTTP キャッシュのパフォーマンスを向上させるため、Vary: Origin レスポンスヘッダーを避けるために quarkus.http.cors.return-exact-origins=false を設定してリテラル * オリジンを返すことを検討してもよいでしょう。

また、開発中にオリジンを設定するのは困難な場合があるため、開発モードですべてのオリジンを許可することを検討してください。

quarkus.http.cors.enabled=true
%dev.quarkus.http.cors.origins=/.*/

CORS フィルターをプログラムで設定する

Configure the CORS filter by using configuration properties or programmatically, but not both.

アプリケーションで CORS ポリシーを適用するには、io.quarkus.vertx.http.security.HttpSecurity CDI イベントを使用して Quarkus CORS フィルターを有効にします。

package org.acme.http.security;

import io.quarkus.vertx.http.security.HttpSecurity;
import jakarta.enterprise.event.Observes;

public class CorsProgrammaticConfig {
    void configure(@Observes HttpSecurity httpSecurity) {
        httpSecurity.cors("https://example.com");
    }
}

Use the io.quarkus.vertx.http.security.CORS builder to create a complete CORS configuration:

package org.acme.http.security;

import io.quarkus.vertx.http.security.CORS;
import io.quarkus.vertx.http.security.HttpSecurity;
import jakarta.enterprise.event.Observes;

public class CorsProgrammaticConfig {
    void configure(@Observes HttpSecurity httpSecurity) {
        httpSecurity.cors(CORS.builder()
                .origin("https://example.com")
                .method("POST")
                .build());
    }
}

Debugging rejected CORS requests

A request rejected by the CORS filter gets a 403 response whose status message starts with CORS Rejected, but the response does not say which part of the request was rejected. The filter logs the reason at the DEBUG level, so enable that level for its logger to see whether the origin, the method, or a request header was not allowed, or why the same-origin check failed:

quarkus.log.category."io.quarkus.vertx.http.runtime.cors.CORSFilter".level=DEBUG

Compare the logged origin, method, and headers with the values of quarkus.http.cors.origins, quarkus.http.cors.methods, and quarkus.http.cors.headers. Browsers also report the failed CORS check in their developer tools console, next to the request that triggered it.