我正在试用我的第一个网络应用程序。使用 Tomcat 7。
我想从 host:port/app1/x/y 转发一些发布数据和身份验证 header 到 host:port/app2/x/y 具有相同的发布数据和 header 。这两个应用程序都在同一台主机上。
/app2 具有基本身份验证。在客户端,代码是
method.addRequestHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(userNPasswd.getBytes())));
我可以通过执行以下操作从/app1 转发到/app2
1) 在/app1 的 doFilter 中实现一个过滤器并执行此操作
ServletContext othercontext = filterConfig.getServletContext().getContext("/app2");
RequestDispatcher dispatcher = othercontext.getRequestDispatcher(req.getRequestURI().replace("/app1", ""));
dispatcher.forward(request, response);
2)在app1..下的WEB-INF/web.xml转发所有(/*)url映射
<filter>
<filter-name>ForwardFilter</filter-name>
<filter-class><my.package.filter.ForwardFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ForwardFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3) 在 conf/server.xml 中的 tomcat 中.. 在同一主机下为/app1 和/app2 定义上下文并关闭 unpack war 等并设置 crossContext = true
<Context path="/app1" docBase="app1" crossContext="true" />
<Context path="/app2" docBase="app2" crossContext="false" />
app1.war 非常简单,只有一个过滤器类和一个映射到转发请求的 web.xml
app2.war 是一个支持 spring 的网络应用
当我使用错误的密码直接向/app2 发出请求时,出现错误
当我转发当前转发的方式(从/app1到/app2)时,它会跳过身份验证并在/app2下开始处理请求。当在/app2 的某个地方时,npe 失败了。它正在尝试从安全上下文中读取用户名(预计 Spring 会启动并设置它)
SecurityContextHolder.getContext().getAuthentication().getName();
我无法更改/app2 下的代码
我希望/app1 是一个非常简单的转发请求..
我不能在 tomcat 前使用重定向或使用 apache 规则重写
如果需要共享更多信息,请告诉我
转发是否也转发所有身份验证 header ,所以就好像请求直接命中/app2 一样?
最佳答案
默认情况下,过滤器不适用于转发。申请转发也需要明确指定
因此,在接收应用程序(此处为 app2)的 WEB-INF/web.xml 中,对于应应用于转发请求的每个过滤器,还要添加以下内容
<filter-mapping>
...
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
...
<filter-mapping>
之后/app2 中所有必需的过滤器也开始执行
关于tomcat - 通过身份验证转发到另一个 webapp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34064850/