SpringBoot/Spring Security

AccessDeniedHandler

콧차뇽 2021. 9. 22.
  1. 개인 공부 목적으로 작성한 포스팅입니다.
  2. 아래 출처를 참고하여 작성하였습니다.

1. AccessDeniedHandler란?

  1. 인가 처리 과정에서 예외가 발생할 경우 예외를 핸들링하는 인터페이스입니다.
  • e.g. 인증은 성공하였지만, 해당 자원에 접근할 권한이 없는 경우 예외가 발생합니다.
  1. ExceptionTranslationFilter가 사용합니다.

2. AccessDeniedHandler 사용방법


2-1. AccessDeniedHandler 인터페이스 구현체 생성

  1. 인가 처리 과정에서 예외가 발생한 경우 해당 구현체의 로직을 타게되어, handle 메소드를 실행하게 됩니다.
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

    static ApiResult<?> E403 = ERROR("Authentication error (cause: forbidden)", HttpStatus.FORBIDDEN);

    private final ObjectMapper om;

    public JwtAccessDeniedHandler(ObjectMapper om) {
        this.om = om;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
            throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setHeader("content-type", "application/json");
        response.getWriter().write(om.writeValueAsString(E403));
        response.getWriter().flush();
        response.getWriter().close();
    }
}

2-2. SecurityConfig에서 .exceptionHandling() 메소드에 등록

//in SecurityConfig.java

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.regexMatcher(UriRegexUtil.RESOURCE_URI_REGEX)
            .securityContext()
            .and()
            .exceptionHandling()
                .authenticationEntryPoint(entryPointUnauthorizedHandler)
                .accessDeniedHandler(jwtAccessDeniedHandler)
            //...
    }

출처

  1. Restful API 구현을 위한 Spring Security 설정해보기 #4 (AuthenticationEntryPoint, AccessDeniedHandler 구현)
  2. Spring Security - ExceptionTranslationFilter

'SpringBoot > Spring Security' 카테고리의 다른 글

ExceptionTranslationFilter  (0) 2021.09.22
AuthenticationEntryPoint  (0) 2021.09.22

댓글