2

我一直致力于开发位于安全代理后面的 CXF Web 服务,该代理要求在服务调用之前进行 HTTP 基本身份验证。这些服务相互之间进行通信,并且需要对请求和响应进行身份验证。

到目前为止,我已经能够通过 HTTPConduit 为请求设置 HTTP 基本身份验证,如下所示:

    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);

上面的方法在每个服务方法调用上都会被调用,我得到了正确的入站消息,形式为

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>
--------------------------------------

但是,响应不包含所需的标头

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

如何修改响应 HTTP 标头?我试过了

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

没有得到想要的结果。

4

1 回答 1

9

一种方法是创建一个CXF 拦截器

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));
    }

}

并将其注册为 out and outFault 拦截器。

    <bean id="basicAuthOutInterceptor class="BasicAuthOutInterceptor" />

    <cxf:bus>
        <cxf:outInterceptors>
            <ref bean="basicAuthOutInterceptor"/>
        </cxf:outInterceptors>
        <cxf:outFaultInterceptors>
            <ref bean="basicAuthOutInterceptor"/>
        </cxf:outFaultInterceptors>        
    </cxf:bus> 
于 2013-05-24T20:35:05.537 回答