It seems spring recommends using Lambda DSL for Security Configuration.
Without using lambdas, I know how to secure my h2-console.
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/h2-console/**").authenticated()
.anyRequest().authenticated()
.and().formLogin()
.and().csrf().ignoringAntMatchers("/h2-console/**")
.and().headers().frameOptions().sameOrigin();
return http.build();
Following the tutorial at the beginning, I tried the following code
http
.authorizeRequests((authz) -> authz
.antMatchers("/h2-console/**").authenticated()
.anyRequest().authenticated()
)
.formLogin()
.csrf().ignoringAntMatchers("/h2-console/**")
.headers().frameOptions().sameOrigin();
and got this error
The method csrf() is undefined for the type FormLoginConfigurer
I also tried lots of other combinations, such as
http
.authorizeRequests(a -> a.anyRequest().permitAll())
.headers().frameOptions().sameOrigin();
or
http
.authorizeRequests(a -> a.anyRequest().permitAll())
.csrf(c - c.ignoringAntMatchers("/h2-console/**"));
or
http
.authorizeRequests(a -> a.anyRequest().permitAll())
.csrf().ignoringAntMatchers("/h2-console/**")
and more and more, none of them works.
How do I secure my h2-console using Lambda DSL
TL;DR: Use the same lambda syntax as for authorizeRequests
:
http.csrf(csrf -> csrf.ignoringAntMatchers("/h2-console/**"))
Details:
You are mixing old syntax (Spring Security 5) with the new (Spring Security 6) syntax.
Old syntax: http.authorizeRequests().antMatchers("...").permitAll().and().csrf().ignoringAntMantchers("...")
is replaced with http.authorizeRequests(a -> a.requestMatchers("...")).csrf(csrf -> csrf.ignoringAntMatchers("...))