Spring security를 적용하기 위해 환경설정 파일을 작성하고 있는데 역시나 에러가 나왔다...
사실 예전 문법을 사용해서 발생한 거라 공식문서를 보면서 만들었으면 된거였는데...
문제는 WebSecurityConfigurerAdapter 이놈이다.
스프링 버전이 최신이라면 WebSecurityConfigurerAdapter는 더 이상 사용하지 않기 때문에 에러가 남!
이건 내가 직접 작성한 코드는 아니고 chat gpt를 사용해서 만든 테스트 코드다.
// SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/user").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout()
.and()
.csrf().disable();
}
}
지피티 선생님에게 여쭤봤더니 그렇다네.
아무튼 WebSecurityConfigurerAdapter대신 SecurityFilterChain를 사용하면 된다!
//The type WebSecurityConfigurerAdapter is deprecated
@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfig {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/user").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout()
.and()
.csrf().disable();
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
참고하자!
'공부 > java & Spring' 카테고리의 다른 글
[Spring boot] IoC(Inversion of Control) 개인공부 (0) | 2023.07.02 |
---|---|
[poi] Spring Boot 엑셀 다운로드 (java, gradle) (0) | 2023.06.23 |
[zxing] Spring boot QR code 생성 (java, gradle) (0) | 2023.06.21 |
[Spring boot build error] visual studio code에서 갑자기 빌드 에러날때 (0) | 2023.05.22 |
[403 Forbidden error] spring post method (axios post request) (1) | 2023.05.14 |
댓글