Don't allow direct calls to Microservices. Only allow through API Gateway

前端 未结 5 1636
走了就别回头了
走了就别回头了 2020-12-25 13:06

Maybe this is a strange question (I\'m new with Microservices). But I\'m looking for some info on how proceed with this. Does not need to be Spring specific, but that\'s the

5条回答
  •  臣服心动
    2020-12-25 14:04

    Hey I finally find a solution to accept request just from the API Gateway by using microservices architecture, for that you can create a filter, and like Zuul act as a proxy, checking the header 'X-Forwarded-Host', if it doesn't match with the gateway service then return an Unauthorised exception.

    public class CustomGatewayFilter extends GenericFilterBean {
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
    
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
    
        String proxyForwardedHostHeader = request.getHeader("X-Forwarded-Host");
    
        if (proxyForwardedHostHeader == null || !proxyForwardedHostHeader.equals(GatewayConstant.getGatewayURL())) {
            UnauthorisedException unauthorisedException = new UnauthorisedException("Unauthorized Access",
                    "Unauthorized Access, you should pass through the API gateway");
            byte[] responseToSend = restResponseBytes(unauthorisedException.getErrorResponse());
            ((HttpServletResponse) response).setHeader("Content-Type", "application/json");
            ((HttpServletResponse) response).setStatus(401);
            response.getOutputStream().write(responseToSend);
            return;
        }
        chain.doFilter(request, response);
    }
    
    private byte[] restResponseBytes(ErrorResponse errorResponse) throws IOException {
        String serialized = new ObjectMapper().writeValueAsString(errorResponse);
        return serialized.getBytes();
    }
    

    }

    do not forget to add your custom filter in SpringSecurity Configuration

    .and().addFilterBefore(new CustomGatewayFilter(), ConcurrentSessionFilter.class);
    

提交回复
热议问题