정수원님의 강의 스프링 시큐리티 완전 정복 [6.x 개정판] 보면서 공부한 내용입니다.
/**
* 예외 처리 - exceptionHandling()
*/
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/login").permitAll()
.requestMatchers("/admin").hasRole("ADMIN") // admin 사용자만 접근 가능, 이외는 인가 예외 발생
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults())
.exceptionHandling(exception -> exception
.authenticationEntryPoint(new AuthenticationEntryPoint() { // 인증 예외
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
System.out.println("exception : " + authException.getMessage());
response.sendRedirect("/login"); // 로그인 페이지로 이동
}
})
.accessDeniedHandler(new AccessDeniedHandler() { // 인가 예외
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
System.out.println("exception : " + accessDeniedException.getMessage());
response.sendRedirect("/denied"); // denied 페이지로 이동
}
})
);
return http.build();
}