原本今天要繼續分享昨天身分驗證的主題,不過剛好Winnie這幾天遇到Spring boot升級後,搭配的Spring security升級遇到了很多改寫的部分,所以今天特別跟大家分享一下 避免大家日後也踩雷 ?!?!
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((auth) -> auth
.anyRequest().authenticated()
)
.httpBasic(withDefaults());
}
}
第一個就遇到的是 咦? 為甚麼 WebSecurityConfigurerAdapter
不能用了 !!!
因為在6.1版本的時候官網希望我們自行實作SecurityFilterChain
來進行配置
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((auth) -> auth
.anyRequest().authenticated()
)
.httpBasic(withDefaults());
return http.build();
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
...
}
如果到6.1版本還這樣寫的話,你就會發現你的程式碼有錯誤
所以升級後要改寫成
csrf(csrf -> csrf.disable())
那更漂亮簡潔的寫法也可以用
csrf(AbstractHttpConfigurer::disable)
authorizeHttpRequests
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/endpoint").hasAuthority("USER")
.anyRequest().authenticated()
)
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
希望大家在要升級的時候可以少踩一點坑
明天再繼續跟大家分享身分驗證吧!!!!!