セキュリティ

このセクションでは、Spring Boot で Spring Security を使用することから生じる質問を含む、Spring Boot を使用する際のセキュリティに関する質問について説明します。

Spring Security の詳細については、Spring Security プロジェクトページを参照してください。

Spring Boot のセキュリティ設定をオフにする

アプリケーションで @Configuration (Javadoc) SecurityFilterChain (Javadoc) Bean とともに定義すると、このアクションによって Spring Boot のデフォルトの Web アプリケーションセキュリティ設定がオフになります。

UserDetailsService の変更とユーザーアカウントの追加

AuthenticationManager (Javadoc) AuthenticationProvider (Javadoc) UserDetailsService (Javadoc) 型の @Bean (Javadoc) を指定した場合、InMemoryUserDetailsManager (Javadoc) のデフォルトの @Bean (Javadoc) は作成されません。つまり、Spring Security の完全な機能セット ( さまざまな認証オプションなど) が利用可能になります。

ユーザーアカウントを追加する最も簡単な方法は、独自の UserDetailsService (Javadoc) Bean を提供することです。

プロキシサーバーの背後で実行しているときに HTTPS を有効にする

すべての主要エンドポイントが HTTPS 経由でのみ利用可能であることを保証することは、どのアプリケーションにとっても重要な作業です。Tomcat をサーブレットコンテナーとして使用する場合、Spring Boot は環境設定を検出すると Tomcat 独自の RemoteIpValve [Apache] (英語) を自動的に追加し、HttpServletRequest (英語) を利用して、それが安全かどうかを報告することができます (実際の SSL 終了を処理するプロキシサーバーの下流であっても)。標準的な動作は、特定のリクエストヘッダー (x-forwarded-for および x-forwarded-proto) の有無によって決まります。これらのヘッダーの名前は慣例的なので、ほとんどのフロントエンドプロキシで動作するはずです。次の例に示すように、application.properties にいくつかのエントリを追加することで、バルブをオンにすることができます。

  • プロパティ

  • YAML

server.tomcat.remoteip.remote-ip-header=x-forwarded-for
server.tomcat.remoteip.protocol-header=x-forwarded-proto
server:
  tomcat:
    remoteip:
      remote-ip-header: "x-forwarded-for"
      protocol-header: "x-forwarded-proto"

(これらのいずれかのプロパティが存在すると、バルブがオンになります。または、WebServerFactoryCustomizer (Javadoc) Bean を使用して TomcatServletWebServerFactory (Javadoc) をカスタマイズし、RemoteIpValve [Apache] (英語) を追加することもできます)

すべての(または一部の)リクエストに対して安全なチャネルをリクエストするように Spring Security を構成するには、次の HttpSecurity (Javadoc) 構成を追加する独自の SecurityFilterChain (Javadoc) Bean を追加することを検討してください。

  • Java

  • Kotlin

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class MySecurityConfig {

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		// Customize the application security ...
		http.requiresChannel((channel) -> channel.anyRequest().requiresSecure());
		return http.build();
	}

}
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.web.SecurityFilterChain

@Configuration
class MySecurityConfig {

	@Bean
	fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
		// Customize the application security ...
		http.requiresChannel { requests -> requests.anyRequest().requiresSecure() }
		return http.build()
	}

}