AuthenticationEntryPoint

public class CustomAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
    private final ObjectMapper objectMapper;

    public CustomAuthenticationEntryPoint(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        ExceptionDto exceptionDto = new ExceptionDto(3, "인증되지 않은 사용자 접근");
        try {
            String jsonResponse = objectMapper.writeValueAsString(exceptionDto);
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            DataBuffer buffer = dataBufferFactory.wrap(jsonResponse.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            return Mono.error(e);
        }
    }
}

cf) webflux기반에서는 throws로 예외를 던지기가 불가하다.

 

ExceptionHandlingFilter

public class CustomExceptionHandlingFilter implements WebFilter {
    private final ObjectMapper objectMapper;

    public CustomExceptionHandlingFilter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        return chain.filter(exchange)
                .onErrorResume(CustomException.class, ex -> {
                    ServerHttpResponse response = exchange.getResponse();
                    response.setStatusCode(ex.getHttpStatus());
                    ExceptionDto exceptionDto = new ExceptionDto(ex.getCode(), ex.getMessage());
                    try {
                        String jsonResponse = objectMapper.writeValueAsString(exceptionDto);
                        DataBufferFactory dataBufferFactory = exchange.getResponse().bufferFactory();
                        DataBuffer buffer = dataBufferFactory.wrap(jsonResponse.getBytes(StandardCharsets.UTF_8));
                        return response.writeWith(Mono.just(buffer));
                    } catch (Exception exception) {
                        return Mono.error(exception);
                    }
                });
    }
}

cf) onErrorResume()의 경우 예외가 발생한 이후의 시점에 존재해야 한다. 즉, 예외가 예상되는 필터 이후에 예외핸들링 필터를 넣어줘야 한다.

 

SecurityConfig

http
        .addFilterAfter(new CustomExceptionHandlingFilter(objectMapper),
                SecurityWebFiltersOrder.LAST);
http
        .exceptionHandling(exceptionHandlingSpec -> exceptionHandlingSpec
                .authenticationEntryPoint(new CustomAuthenticationEntryPoint(objectMapper)));

+ Recent posts