스프링에서 제공해주는 인증(로그인, 회원가입)과 인가(페이지 접근 권한)에 대한 처리를 위임하는 프레임워크.
Filter는 Dispatcher Servlet으로 가기 전에 가장 먼저 URL 요청을 받는다.
WebSecurityConfigurerAdapter 는 스프링 시큐리티 5.7.0 버전 이후로 deprecated 되었다. 공식문서를 참고하여 설정하자.
@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();
}
}