특정 자원 접근 시 발생하는 있는 거절 종류 ( 토큰은 정상 )
- 로그인조차 되지 않은 채 로그인이 필요한 리소스에 접근 시 AuthenticationException -> 인증 실패
- 로그인하였으나 권한 없는 관계로 인한 AccessDeniedException -> 인가 실패
*로그인 은 정상 토큰으로 인증객체 생성 완료된 상태
*비로그인 은 Anonymous인증객체가 생성 완료된 상태
더보기
각각 어떤 식으로 에러 응답을 처리할까?
인가 실패
CustomAccessDeniedHandler
권한 없는 자원 접근 발생하는 예외( AccessDeniedException )에 대하여 AccessDeinedHandler 인터페이스를 구현하여 처리
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
log.error("유효하지 않은 권한을 지닌 사용자의 요청으로 인한 거절");
ObjectMapper om= new ObjectMapper();
ResultResDto resultResDto = ResultResDto.builder()
.msg(RESULTCODE.RESULT_DENYAUTHORIZATION.getMsg())
.code(RESULTCODE.RESULT_DENYAUTHORIZATION.getResultCode())
.build()
;
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
om.writeValue(response.getOutputStream(), resultResDto);
}
}
인증 실패
CustomAuthenticationEntryPoint
인증 실패(비로그인= 익명의 사용자 접근)로 인한 예외( AuthenticationException )에 대하여 AuthenticationEntryPoint 인터페이스를 구현하여 처리
@Slf4j
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
log.error("유효하지 않은 권한으르 지닌 사용자의 요청입니다.");
ObjectMapper om= new ObjectMapper();
ResultResDto resultResDto = ResultResDto.builder()
.msg(RESULTCODE.RESULT_ASKLOGIN.getMsg())
.code(RESULTCODE.RESULT_ASKLOGIN.getResultCode())
.build()
;
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
om.writeValue(response.getOutputStream(), resultResDto);
}
}
config 파일 내 선언
@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
public class SpringSecurityConfig {
생략..
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
생략...
.exceptionHandling(authenticationManger -> authenticationManger
.authenticationEntryPoint(new CustomAuthenticationEntryPoint()) //★AuthenticationException 처리
.accessDeniedHandler(new CustomAccessDeniedHandler()) //★ AccessDeniedException 처리
)
;
return http.build();
}
'SpringBoot > SpringSecurity' 카테고리의 다른 글
JwtAuthenticationFilter 내 발생 가능한 Exception 공통 처리 (0) | 2023.10.19 |
---|---|
[이슈] AuthenticationProvider 인터페이스 구현 후 적용되지 않는 상황 처리 (0) | 2023.10.19 |