How to change HTTP headers for a JAX-WS response in CXF?

I worked on creating CXF web services that are behind a security proxy that requests HTTP authentication pre-authentication. These services communicate with each other and require authentication for request and response.

So far, I have been able to set up basic HTTP authentication through HTTPConduit for the request as follows:

Client client = ClientProxy.getClient(port); HTTPConduit conduit = (HTTPConduit) client.getConduit(); AuthorizationPolicy authorizationPolicy = new AuthorizationPolicy(); authorizationPolicy.setUserName(username); authorizationPolicy.setPassword(password); authorizationPolicy.setAuthorizationType("Basic"); conduit.setAuthorization(authorizationPolicy); 

The above method is called every time the service method is called, and I get the correct incoming messages in the form

 INFO: Inbound Message ---------------------------- ID: 1 Address: http://someURL/someService?wsdl Encoding: UTF-8 Http-Method: POST Content-Type: text/xml; charset=UTF-8 Headers: {Accept=[*/*], Authorization=[Basic {TOKEN}], cache-control=[no-cache], connection=[keep-alive], Content-Length=[735], content-type=[text/xml; charset=UTF-8], pragma=[no-cache], ...} Payload: <soap:Envelope>...</soap:Envelope> -------------------------------------- 

The answer, however, does not contain the required headers.

 INFO: Outbound Message --------------------------- ID: 2 Encoding: UTF-8 Content-Type: text/xml Headers: {} Payload: <soap:Envelope/">...</soap:Envelope> -------------------------------------- 

How to change HTTP response headers? I tried

 ((BindingProvider)port).getResponseContext().put( MessageContext.HTTP_RESPONSE_HEADERS, Collections.singletonMap("Authentication", Collections.singletonList("Basic "+token))); 

without getting the desired result.

+1
source share
1 answer

One approach would be to create a CXF interceptor.

 public class BasicAuthOutInterceptor extends AbstractPhaseInterceptor<Message> { public BasicAuthOutInterceptor() { super(Phase.PRE_STREAM); } @Override public void handleMessage(Message message) throws Fault { String token = "basic auth token"; @SuppressWarnings("unchecked") Map<String, List<String>> headers = (Map<String, List<String>>) message .get(Message.PROTOCOL_HEADERS); if (headers == null) { headers = new TreeMap<String, List<String>>( String.CASE_INSENSITIVE_ORDER); message.put(Message.PROTOCOL_HEADERS, headers); } headers.put("Authentication", Arrays.asList("Basic "+ token)); } } 

and register it as an out and outFault interceptor.

  <bean id="basicAuthOutInterceptor class="BasicAuthOutInterceptor" /> <cxf:bus> <cxf:outInterceptors> <ref bean="basicAuthOutInterceptor"/> </cxf:outInterceptors> <cxf:outFaultInterceptors> <ref bean="basicAuthOutInterceptor"/> </cxf:outFaultInterceptors> </cxf:bus> 
+7
source

Source: https://habr.com/ru/post/945632/


All Articles