Spring Boot 3.1にアップグレードする

Spring Bootの3.1がリリースされたため、早速アップグレードしたところ、Spring Securityのバージョンが6.1になっていた。

その結果、このクラスでは以下のメソッドが非推奨になった。
.exceptionHandling()
.cors()
.csrf()
.formLogin()
.httpBasic()
.authorizeExchange()
.and()

@Bean
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
    return http
            .exceptionHandling()
            .authenticationEntryPoint((swe, e) -> {
                return Mono.fromRunnable(() -> {
                    swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                });
            }).accessDeniedHandler((swe, e) -> {
                return Mono.fromRunnable(() -> {
                    swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                });
            }).and()
            .cors().configurationSource(corsConfigurationSource())
            .and().csrf().disable()
            .formLogin().disable()
            .httpBasic().disable()
            .authenticationManager(authenticationManager)
            .securityContextRepository(securityContextRepository)
            .authorizeExchange()
            .pathMatchers(HttpMethod.OPTIONS).permitAll()
            .pathMatchers("/crawler-api/login").permitAll()
            .pathMatchers("/crawler-api/signup").permitAll()
            .pathMatchers("/crawler-api/users*").hasAuthority("ROLE_USER")
            .pathMatchers("/crawler-api/novels*").hasAuthority("ROLE_USER")
            .anyExchange().authenticated()
            .and().build();
}

非推奨になったメソッドには新たにラムダ式で記述出来る同名のメソッドが追加されている。今後はそちらを使用する。

新しいメソッドに置き換えると下記の通りとなる。

.exceptionHandling(exceptionHandling -> exceptionHandling
        .authenticationEntryPoint((swe, e) -> {
            return Mono.fromRunnable(() -> {
                swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            });
        }).accessDeniedHandler((swe, e) -> {
            return Mono.fromRunnable(() -> {
                swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            });
        }))
.csrf(csrf -> csrf.disable())
.formLogin(formLogin -> formLogin.disable())
.httpBasic(httpBasic -> httpBasic.disable())
.authenticationManager(authenticationManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange(exchanges -> exchanges
        .pathMatchers(HttpMethod.OPTIONS).permitAll()
        .pathMatchers("/crawler-api/login").permitAll()
        .pathMatchers("/crawler-api/signup").permitAll()
        .pathMatchers("/crawler-api/users*").hasAuthority("ROLE_USER")
        .pathMatchers("/crawler-api/novels*").hasAuthority("ROLE_USER")
        .anyExchange().authenticated())
.build();

cors()についてはCorsConfigurationSourceのBeanが定義されていれば自動的に読み込まれるとのことなので、SecurityWebFilterChainからは削除した。
また、新しいメソッドを置き換えた結果、.and()は不要になった。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください