- 기존 FilterChain 내에서 앞뒤로 원하는 Filter를 붙일 수 있다.
public class RequestValidationFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,
ServletException {
var httpRequest = (HttpServletRequest) request;
var httpResponse = (HttpServletResponse) response;
String requestId = httpRequest.getHeader("Request-Id");
// if (requestId == null || requestId.isBlank()) {
// httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
// return;
// }
filterChain.doFilter(request, response);
}
}
뒤에 붙일 필터를 정의한다.
public class AuthenticationLoggingFilter implements Filter {
private final Logger logger =
Logger.getLogger(AuthenticationLoggingFilter.class.getName());
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,
ServletException {
var httpRequest = (HttpServletRequest) request;
String requestId = httpRequest.getHeader("Request-Id");
logger.info("Successfully authenticated request with id " + requestId);
filterChain.doFilter(request, response);
}
}
아래와 같이 BasicAuthenticationFilter 앞 뒤로 원하는 필터 주입할 수 있다.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.addFilterBefore(new RequestValidationFilter(), BasicAuthenticationFilter.class)
.addFilterAfter(new AuthenticationLoggingFilter(), BasicAuthenticationFilter.class)
아래는 Header에 키를 체크하는 필터의 예시
@Component
public class StaticKeyAuthenticationFilter implements Filter {
@Value("${authorization.key}")
private String authorizationKey;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
var httpRequest = (HttpServletRequest) request;
var httpResponse = (HttpServletResponse) response;
String authentication = httpRequest.getHeader("Authorization");
if (authorizationKey.equals(authentication)) {
filterChain.doFilter(request, response);
} else {
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
반응형