출처 - https://devlog-wjdrbs96.tistory.com/434
WebSecurityConfigurerAdapter Deprecated 해결하기
최근에 Spring Security를 설정해보려고 WebSecurityConfigurerAdapter를 사용하려 보니 Deprecated가 되어 있었는데요.
@RequiredArgsConstructor
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final ObjectMapper objectMapper;
private final JwtAuthenticationFilter jwtAuthenticationFilter;
@Override
public void configure(WebSecurity web) {
web.ignoring().mvcMatchers(
"/error",
"/favicon.ico",
"/swagger-ui.html",
"/swagger/**",
"/swagger-resources/**",
"/webjars/**",
"/v2/api-docs"
);
web.ignoring().antMatchers(
"/api/v2//login/**"
);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/api/v2/**").hasAuthority(USER.name());
http.httpBasic().disable()
.formLogin().disable()
.cors().disable()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.anyRequest().permitAll()
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
http.exceptionHandling()
.authenticationEntryPoint(((request, response, authException) -> {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
objectMapper.writeValue(
response.getOutputStream(),
ExceptionResponse.of(ExceptionCode.FAIL_AUTHENTICATION)
);
}))
.accessDeniedHandler(((request, response, accessDeniedException) -> {
response.setStatus(HttpStatus.FORBIDDEN.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
objectMapper.writeValue(
response.getOutputStream(),
ExceptionResponse.of(ExceptionCode.FAIL_AUTHORIZATION)
);
}));
}
}
위와 같은 많은 설정들을 WebSecurityConfigurerAdapter를 extends 해서 configure 메소드를 오버라이딩 해서 구현했었습니다.
하지만 이제 WebSecurityConfigurerAdapter가 Deprecated가 되어서 사용할 수 없다보니 다른 것을 사용해서 구현해야 합니다.
WebSecurityConfigurerAdapter 공식문서를 보면 위와 같이 나와 있습니다.
Deprecated.
Use a SecurityFilterChain Bean to configure HttpSecurity or a WebSecurityCustomizer Bean to configure WebSecurity
요약하면 WebSecurityConfigurerAdapter가 Deprecated 되었으니 SecurityFilterChain를 Bean으로 등록해서 사용해라 입니다.
위의 내용만 보면 감이 잘 오지 않아서 Spring Security 공식문서를 보면 어떻게 설정해야 하는지 나와있습니다.
기존 코드의 설정을 바꿔보면?
@RequiredArgsConstructor
@EnableWebSecurity
public class SecurityConfig {
private final ObjectMapper objectMapper;
private final JwtAuthenticationFilter jwtAuthenticationFilter;
@Bean
public WebSecurityCustomizer configure() {
return (web) -> web.ignoring().mvcMatchers(
"/v3/api-docs/**",
"/swagger-ui/**",
"/api/v1/login" // 임시
);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/api/v1/**").hasAuthority(USER.name())
.and()
.httpBasic().disable()
.formLogin().disable()
.cors().disable()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.anyRequest().permitAll()
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(((request, response, authException) -> {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
objectMapper.writeValue(
response.getOutputStream(),
ExceptionResponse.of(ExceptionCode.FAIL_AUTHENTICATION)
);
}))
.accessDeniedHandler(((request, response, accessDeniedException) -> {
response.setStatus(HttpStatus.FORBIDDEN.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
objectMapper.writeValue(
response.getOutputStream(),
ExceptionResponse.of(ExceptionCode.FAIL_AUTHORIZATION)
);
})).and().build();
}
}
기존에 위에 있던 설정들을 최신 Security에 맞게 바꿔보면 위와 같이 바꿀 수 있습니다.
Reference
- https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.html
- https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter
WebSecurityConfigurerAdapter (spring-security-docs 5.7.2 API)
Provides a convenient base class for creating a WebSecurityConfigurer instance. The implementation allows customization by overriding methods. Will automatically apply the result of looking up AbstractHttpConfigurer from SpringFactoriesLoader to allow deve
docs.spring.io
'programming study > B-Spring Security' 카테고리의 다른 글
오류 해결 - 순환참조 The dependencies of some of the beans in the application context form a cycle (0) | 2023.05.02 |
---|---|
spring security와 OAuth2 (0) | 2023.01.14 |
스프링 시큐리티 사용 이유 (0) | 2023.01.13 |
Spring Security 로그인 동작 흐름 (0) | 2022.12.29 |
Spring Security 사용하기 (0) | 2022.12.27 |