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)));
'Spring Boot > MSA' 카테고리의 다른 글
spring security in gateway-webflux (0) | 2024.10.05 |
---|---|
jpa 연관관계 설정 in msa (0) | 2024.09.29 |
마이크로서비스로의 전환 (feat. 도메인 주도 설계) (0) | 2024.09.25 |
데이터베이스 in MSA (0) | 2024.09.24 |
마이크로서비스 핵심 원칙 (0) | 2024.09.23 |