如何解决如何防止HTTP客户端不通过网关直接向微服务发出请求
如何防止HTTP客户端不通过网关向微服务发出请求
但微服务之间可以不通过网关进行通信?
请帮忙
我在我的微服务中添加了这个过滤器,以防止客户端直接向微服务发送请求,但它也阻止了微服务之间的通信
public class CustomGatewayFilter extends GenericFilterBean {
private static final Logger LOG = LoggerFactory.getLogger(CustomGatewayFilter.class);
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("localhost:8090")) {
UnauthorisedException unauthorisedException =
new UnauthorisedException("Unauthorized Access,you should pass through the API gateway","Unauthorized Access");
LOG.info("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();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。