java - 如何在 Java EE 应用程序中使用丰富的 header 将请求代理到另一个位置

标签 java java-ee-6 netflix-zuul

我面临以下问题。我需要在 websphere(没有 Spring)上运行的 java EE 应用程序中创建一种方法来将请求代理到另一个位置并使用不记名 token 丰富 header 。

看下面的例子

GET request: http://servicehost.com/proxy/targetapi/userresource

需要转发至

GET request: http://othertargethost.com/targetapi/userresource with Authorization: Bearer randomtoken

我在另一个应用程序中解决了这个问题,但这是一个使用 Netflix Zuul 和 spring-cloud-starter-netflix-zuul 的 Spring Boot 应用程序。

但是现在我处于严格的 EE 环境中,根本不允许使用 spring。我还没有找到任何关于如何在纯 EE 上下文中设置或配置 netflix zuul 的好的文档或示例。

我还需要哪些其他替代方案来解决这个问题?我在想以下问题

  • 在 **/proxy/* 上设置 Servlet 并创建一个用于转发的过滤器
  • 在互联网上搜索类似于 Zuul 的东西,并提供更好的文档以在 EE 中运行它
  • ...

我真的很感激任何能指引我正确方向的东西。

Jersey web service proxy这对我来说不是一个解决方案,因为这是在特定端点上并使用特定 http 方法确定的

GET request: http://servicehost.com/proxy/targetapi/userresource

可能

GET request: http://servicehost.com/proxy/targetapi/contractresource

GET request: http://servicehost.com/proxy/specialapi/userresource

并且它需要能够处理 GET、POST、PUT 和 DELETE

最佳答案

我无法在 EE 中使用 Zuul,所以我只有一种办法,那就是编写自己的 servlet

@WebServlet(name = "ProxyServlet", urlPatterns = {"/proxy/*"})
public class ProxyServlet extends HttpServlet {

    public static final String SESSION_ID_PARAM = "delijnSessionId";

    @Inject
    private Logger logger;

    @Inject
    private ProxyProperties proxyProperties;

    @Inject
    private SecurityService securityService;

    @Inject
    private ProxyHttpClientFactory proxyHttpClientFactory;

    @Inject
    private StreamUtils streamUtils;

    @Override
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        proxy(httpServletRequest, httpServletResponse);
    }

    @Override
    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        proxy(httpServletRequest, httpServletResponse);
    }

    @Override
    protected void doPut(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        proxy(httpServletRequest, httpServletResponse);
    }

    @Override
    protected void doDelete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        proxy(httpServletRequest, httpServletResponse);
    }

    private void proxy(HttpServletRequest request, HttpServletResponse response) {
        try {
            String requestUrl = request.getRequestURI();
            String method = request.getMethod();
            String sessionId = getSessionId(request);

            String protocol = proxyProperties.getProperty(ProxyProperties.PROXY_PROTOCOL);
            String server = proxyProperties.getProperty(ProxyProperties.PROXY_SERVER);
            String port = proxyProperties.getProperty(ProxyProperties.PROXY_PORT);

            String newPath = requestUrl.replaceFirst(".*/proxy", "");

            URI uri = new URI(protocol, null, server, Integer.parseInt(port), newPath, request.getQueryString(), null);

            ProxyHttpMethod proxyRequest = new ProxyHttpMethod(method);
            proxyRequest.setURI(uri);
            copyBodyFromRequest(request, method, proxyRequest);
            copyHeadersFromRequest(request, proxyRequest);
            enrichWithAccessToken(proxyRequest, sessionId);

            try (CloseableHttpClient client = proxyHttpClientFactory.produce()) {
                logger.info("uri [{}]", uri);
                logger.info("method [{}]", method);
                execute(client, proxyRequest, response);
            } catch (IOException e) {
                throw new TechnicalException(e);
            }
        } catch (URISyntaxException | IOException e) {
            throw new TechnicalException(e);
        }
    }

    private void execute(CloseableHttpClient client, ProxyHttpMethod proxyHttpMethod, HttpServletResponse response) {
        try (CloseableHttpResponse proxyResponse = client.execute(proxyHttpMethod)) {
            int statusCode = proxyResponse.getStatusLine().getStatusCode();
            if (statusCode >= 200 || statusCode < 300) {
                response.setStatus(statusCode);
                HttpEntity entity = proxyResponse.getEntity();
                if(entity != null){
                    String result = streamUtils.getStringFromStream(entity.getContent());
                    logger.trace("result [" + result + "]");
                    response.getWriter().write(result);
                    response.getWriter().flush();
                    response.getWriter().close();
                }
            } else {
                throw new TechnicalException("[" + statusCode + "] Error retrieving access token");
            }
        } catch (IOException e) {
            throw new TechnicalException(e);
        }
    }

    private void enrichWithAccessToken(ProxyHttpMethod proxyRequest, String sessionId) {
        Optional<TokenDto> token = securityService.findTokenBySessionIdWithRefresh(sessionId);
        if (token.isPresent()) {
            String accessToken = token.get().getAccessToken();
            logger.trace(String.format("Enriching headers with: Authorization Bearer %s", accessToken));
            proxyRequest.setHeader("Authorization", "Bearer " + accessToken);
        } else {
            logger.info(String.format("No token found in repository for sessionId [%s]", sessionId));
            throw new RuntimeException("No token found in repository");
        }
    }

    private void copyBodyFromRequest(HttpServletRequest request, String method, ProxyHttpMethod proxyRequest) throws IOException {
        if ("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) {
            String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            StringEntity entity = new StringEntity(body);
            proxyRequest.setEntity(entity);
        }
    }

    private void copyHeadersFromRequest(HttpServletRequest request, ProxyHttpMethod proxyRequest) {
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            if (!"host".equalsIgnoreCase(headerName) && !"Content-Length".equalsIgnoreCase(headerName)) {
                proxyRequest.setHeader(headerName, request.getHeader(headerName));
            }
        }
    }

    private String getSessionId(HttpServletRequest request) {
        String sessionId = "";
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if (SESSION_ID_PARAM.equals(cookie.getName())) {
                    sessionId = cookie.getValue();
                }
            }
            return sessionId;
        }
        return "";
    }
}

不理想,但我没有看到其他出路

关于java - 如何在 Java EE 应用程序中使用丰富的 header 将请求代理到另一个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61252851/

相关文章:

java - 如何使用 HttpResponse 检查响应正文是 SOAP 消息还是 XML 消息或 XSD 文档还是 WSDL 文档

java - 如何在 java ee 6 框架中的 JAX-WS Web 服务中保存数据?

java - 基于 Zuul 的路由中的超时异常

java - 左手坐标系的历史原因

java - 从 Java Iterator 中随机跳过 'X' 百分比的单词

java - 示例套接字应用程序不起作用

java - 使用 Eclipse 启动 Web Service Explorer 时出现错误 500

java - JAAS - Java EE 6 中的 Java 编程安全性(没有 @DeclareRoles)

java - 由于找不到 `HttpServletRequest` 类,@EnableZuulProxy 不起作用

spring - Zuul spring security 并在请求中添加附加参数