问题
I have a ProxyServlet
to handle requests to another server (which uses HTTP Basic Authentication) sent from my Application, and i want to add the header manually before the Servlet fires the actual request so the User wont have to enter any credentials.
I have tried something like this code below using 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);
}
}
It doesnt seem to work, when i try to access it, shows a pop-up and asks for credentials for the remote server.
My web.xml contains
<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>
Is there any other way to make this work?
Thanks!
回答1:
Solution was to override the methods getHeader(String name)
, getHeaders(String name)
and getHeaderNames()
as shown below. This depends also on how the implementation is looking for headers. In this case ProxyServlet
is looking via 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);
}
};
来源:https://stackoverflow.com/questions/44178257/add-http-basic-authentication-to-servletrequest