有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java WSSecurity UsernameToken与Apache CXF

我有一个与SOAP服务交互的java应用程序。我使用WSDL通过CXF生成java客户机,但我需要使用ws-security对我的调用进行身份验证。我正在寻找一种只使用代码的方法来实现这一点,我没有任何xml配置。这就是我尝试过的:

Map ctx = ((BindingProvider)port).getRequestContext();
ctx.put("ws-security.username", "joe");
ctx.put("ws-security.password", "joespassword");
port.makeSoapCall();

但是我得到了一个无效WS-Security头的解析错误。正确的方法是什么

在SOAP UI中,我可以通过右键单击SOAP头、单击“添加WSS UsernameToken”并选择“密码文本”轻松做到这一点


共 (2) 个答案

  1. # 1 楼答案

    您正在按照共享的代码使用WS-SecurityPolicy。如何仅使用WS-Security并使用WSS4JOutInterceptor跨usernametoken发送

    查看apache cfx ws-security guide中的“通过API添加拦截器”部分:http://cxf.apache.org/docs/ws-security.html

    根据上面的apache cxf文档,这就是需要做的事情。您可能只需要输出拦截器路径

    在客户端,您可以使用ClientProxy助手获取对CXF端点的引用:

    import org.apache.cxf.frontend.ClientProxy;
    ...
    
    GreeterService gs = new GreeterService();
    Greeter greeter = gs.getGreeterPort();
    ...
    org.apache.cxf.endpoint.Client client = ClientProxy.getClient(greeter);
    org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint();
    

    现在可以添加拦截器了:

    import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;
    import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
    ...
    
    Map<String,Object> inProps = new HashMap<String,Object>();
    ... // how to configure the properties is outlined below;
    
    WSS4JInInterceptor wssIn = new WSS4JInInterceptor(inProps);
    cxfEndpoint.getInInterceptors().add(wssIn);
    
    Map<String,Object> outProps = new HashMap<String,Object>();
    outProps.put("action", "UsernameToken Timestamp");
    outProps.put("passwordType", "PasswordDigest"); //remove this line if want to use plain text password
    outProps.put("user", "abcd");
    outProps.put("passwordCallbackClass", "demo.wssec.client.UTPasswordCallback");
    
    WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);
    cxfEndpoint.getOutInterceptors().add(wssOut);
    

    您需要在上面的示例中编写密码回调类(UTPasswordCallback)

    ApacheCXF在这里有一个完整的用户名令牌示例:http://svn.apache.org/repos/asf/cxf/trunk/distribution/src/main/release/samples/ws_security/ut/

    从上面的链接浏览到客户端文件夹(src/main/java/demo/wssec/client),以获取用户名令牌和UTPasswordCallback代码

    编辑:如果您的wsdl希望密码为纯文本,则只需从代码中删除以下行: 输出。put(“passwordType”、“PasswordDigest”)