gpt4 book ai didi

java - 将 Http 基本身份验证添加到 servletRequest

转载 作者:行者123 更新时间:2023-12-02 13:04:53 26 4
gpt4 key购买 nike

我有一个 ProxyServlet 来处理从我的应用程序发送到另一台服务器(使用 HTTP 基本身份验证)的请求,并且我想在 Servlet 触发实际请求之前手动添加 header ,以便用户无需输入任何凭据。

我已经使用 HttpServletRequestWrapper 尝试了类似下面的代码

public class DataServlet extends ProxyServlet {
@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
throws ServletException, IOException {

final SystemCredentials credentials = new SystemCredentials("username", "password");

HttpServletRequestWrapper wrap = new HttpServletRequestWrapper(servletRequest){

@Override
public String getHeader(String name) {
if (name.equals("Authorization")){
String encoding = Base64.getEncoder().encodeToString((credentials.getUser().concat(":").concat(credentials.getPassword()).getBytes()));
return "Basic " + encoding;
} else
return super.getHeader(name);
}

};

super.service(wrap, servletResponse);

}
}

它似乎不起作用,当我尝试访问它时,会显示一个弹出窗口并要求提供远程服务器的凭据。

我的 web.xml 包含

<servlet>
<servlet-name>data</servlet-name>
<servlet-class>foo.package.servlet.DataServlet</servlet-class>
<init-param>
<param-name>targetUri</param-name>
<param-value>http://fooServer/DataServer</param-value>
</init-param>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>data</servlet-name>
<url-pattern>/DataServer/*</url-pattern>
</servlet-mapping>

还有其他方法可以实现这个功能吗?

谢谢!

最佳答案

解决方案是重写方法 getHeader(String name) , getHeaders(String name)getHeaderNames()如下所示。这还取决于实现如何寻找 header 。在这种情况下ProxyServlet正在寻找Enumeration<String> getHeaders(String name) .

HttpServletRequestWrapper wrap = new HttpServletRequestWrapper(servletRequest){


@Override
public String getHeader(String name) {

if (name.equals(HttpHeaders.AUTHORIZATION)){
String encoding = Base64.getEncoder().encodeToString((credentials.getUser().concat(":").concat(credentials.getPassword()).getBytes()));
return "Basic " + encoding;
}
return super.getHeader(name);
}

@Override
public Enumeration<String> getHeaders(String name) {
if (name.equals(HttpHeaders.AUTHORIZATION)){
List<String> temp = new ArrayList<>();
String encoding = Base64.getEncoder().encodeToString((credentials.getUser().concat(":").concat(credentials.getPassword()).getBytes()));
temp.add("Basic " + encoding);
return Collections.enumeration(temp);
}
return super.getHeaders(name);
}

@Override
public Enumeration<String> getHeaderNames() {
// TODO Auto-generated method stub
List<String> temp = Collections.list(super.getHeaderNames());
temp.add(HttpHeaders.AUTHORIZATION);
return Collections.enumeration(temp);

}

};

关于java - 将 Http 基本身份验证添加到 servletRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44178257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com