タイトル: Spring SecurityのBasic認証の無効化
SEOタイトル: Spring Security の Basic 認証を無効化する正しい方法(依存削除 / 設定 / プロパティ)
| この記事の要点 |
|
なぜ Basic 認証ダイアログが出るのか
Spring Boot で spring-boot-starter-security を依存に追加すると、自動設定で全エンドポイントに HTTP Basic 認証 が掛かります。アクセスすると次の通知:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="Realm"
# 起動ログにランダム生成パスワード
Using generated security password: 12345678-abcd-1234-efgh-1234567890ab
This generated password is for development use only.
方法1: SecurityFilterChain で完全制御(推奨)
Spring Security 6 / Spring Boot 3 系の書き方:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // API なら無効化
.httpBasic(httpBasic -> httpBasic.disable()) // ★ Basic 認証無効化
.formLogin(form -> form.disable()) // フォーム認証も無効化
.authorizeHttpRequests(auth -> auth
.anyRequest().permitAll() // すべて許可
);
return http.build();
}
}
Spring Security 5 系の書き方
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic().disable()
.formLogin().disable()
.authorizeRequests()
.anyRequest().permitAll();
}
}
方法2: 一部 URL のみ認証不要にする
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
// 認証不要パス
.requestMatchers("/", "/login", "/register", "/css/**", "/js/**").permitAll()
.requestMatchers("/api/public/**").permitAll()
.requestMatchers(HttpMethod.GET, "/products/**").permitAll()
// 管理者専用
.requestMatchers("/admin/**").hasRole("ADMIN")
// それ以外は認証必須
.anyRequest().authenticated()
)
.formLogin(form -> form.loginPage("/login"))
.logout(logout -> logout.permitAll());
return http.build();
}
方法3: 起動時パスワードを固定(暫定回避)
本番では絶対に使わないこと。開発確認用の暫定:
# application.yml
spring:
security:
user:
name: admin
password: secret # 本番厳禁。秘匿情報は環境変数で
roles: USER
方法4: Spring Security の依存自体を外す(非推奨)
Spring Security が提供する CSRF 保護や CORS、ヘッダーセキュリティも同時に消えるので非推奨:
API 専用アプリでの典型構成
@Configuration
@EnableWebSecurity
public class ApiSecurityConfig {
@Bean
public SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // ステートレス API
.sessionManagement(s -> s.sessionCreationPolicy(
SessionCreationPolicy.STATELESS)) // セッション持たない
.httpBasic(httpBasic -> httpBasic.disable())
.formLogin(form -> form.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll() // 認証エンドポイントは公開
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
)
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
CORS 設定(無効化と一緒にやることが多い)
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://app.example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(List.of("*"));
config.setAllowCredentials(true);
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(csrf -> csrf.disable())
...
return http.build();
}
動作確認
# 認証無し
curl http://localhost:8080/api/public/hello
# 200 OK が返る
# Authorization なしで認証必須エンドポイント
curl -i http://localhost:8080/api/users
# HTTP/1.1 401 Unauthorized
# Basic 認証で
curl -u admin:secret http://localhost:8080/api/users
# Bearer Token で(JWT 等)
curl -H "Authorization: Bearer eyJhbGc..." http://localhost:8080/api/users
FAQ
Q: テスト時だけ無効化したい
A: @SpringBootTest + @AutoConfigureMockMvc(addFilters = false) でフィルタチェインをスキップ。または専用 @TestConfiguration で permitAll 設定。
Q: 認証無効化したのに 401 が返る
A: ① @EnableWebSecurity + Bean 定義の両方が必要、② actuator エンドポイントは別途 management.endpoints.web.exposure.include で公開、③ Spring Boot 3 系で WebSecurityConfigurerAdapter を使うと無視される(削除済)。
Q: ヘッダー WWW-Authenticate: Basic をレスポンスから消したい
A: httpBasic.disable() + 401 を出す箇所で BasicAuthenticationEntryPoint ではなく HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED) を使う。