본문 바로가기
SpringBoot/Spring Security

AuthenticationEntryPoint

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

1. AuthenticationEntryPoint란 ?

  1. 인증 처리 과정에서 예외가 발생한 경우 예외를 핸들링하는 인터페이스입니다.
  • e.g. AuthenticationException(인증되지 않은 요청)인 경우 AuthenticationEntryPoint를 사용하여 처리
  1. ExceptionTranslationFilter가 사용합니다.

2. AuthenticationEntryPoint 사용방법


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

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

    static ApiResult<?> E401 = ERROR("Authentication error (cause: unauthorized)", HttpStatus.UNAUTHORIZED);

    private final ObjectMapper om;

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

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setHeader("content-type", "application/json");
        response.getWriter().write(om.writeValueAsString(E401));
        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
AccessDeniedHandler  (0) 2021.09.22