권한이 없는 상태에서 권한이 필요한 작업을 요청하면 웹 페이지에서는 HTTP ERROR 500가 발생함.
콘솔에는 아래와 같이 출력됨.
ERROR 3288 --- [thymeleaf-board] [nio-8080-exec-8] c.p.t.exception.GlobalExceptionHandler : 예상치 못한 에러 발생 : Access Denied
ERROR 3288 --- [thymeleaf-board] [nio-8080-exec-8] c.p.t.exception.GlobalExceptionHandler : 에러의 원인 :
org.springframework.security.authorization.AuthorizationDeniedException: Access Denied

@PreAuthorize에노테이션으로 인해 요청을 막으면서 Access Denied이 발생한 것.@ExceptionHandler(AuthorizationDeniedException.class)
public String handleAccessDenied(RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("errorMsg", "권한이 없어요.");
return "redirect:/user/login";
}
@ControllerAdvice or @RestcontrollerAdvice에노테이션이 적용된 클래스에@ExceptionHandler(AuthorizationDeniedException.class)을 이용해서 메서드로 예외처리를 해주면 됨.RedirectAttributes를 사용해서 일회성 메시지도 간단히 출력할 수 있음.AccessDeniedHandler 인터페이스를 구현해서 커스텀 핸들러를 만들어서 Security 설정 파일에 넣어주면 됨.public class CustomAccessDeniedHandler implements AccessDeniedHandler {
private String errorPage;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
String deniedUrl = errorPage + "?exception=" + accessDeniedException.getMessage();
response.sendRedirect(deniedUrl);
}
public void setErrorPage(String errorPage) {
this.errorPage = errorPage;
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig {
...
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(
....
http.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler())
return http.build();
}
@Bean
public AccessDeniedHandler accessDeniedHandler() {
CustomAccessDeniedHandler accessDeniedHandler = new CustomAccessDeniedHandler();
accessDeniedHandler.setErrorPage("/denied");
return accessDeniedHandler;
}
}