Untitled
unknown
plain_text
7 months ago
1.4 kB
2
Indexable
Never
@RequiredArgsConstructor public class test extends OncePerRequestFilter { public static final String X_API_KEY = "x-api-key"; private final String configApiKey; @Override protected void doFilterInternal(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException { if (SecurityContextHolder.getContext().getAuthentication() instanceof AuthenticationToken) { log.debug("It is already authenticated"); filterChain.doFilter(request, response); return; } String key = request.getHeader(X_API_KEY); if (StringUtils.hasText(key) && configApiKey.equals(key)) { filterChain.doFilter(request, response); } else { sendError(response); } } private void sendError(HttpServletResponse response) throws IOException { response.resetBuffer(); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.getOutputStream().print( new ObjectMapper().writeValueAsString(new ResultDTO(HttpStatus.UNAUTHORIZED))); response.flushBuffer(); } }
Leave a Comment