Axis2 with Rampart: Undefined 'Пространство имен политики безопасности не может быть нулевым.' свойство ресурса

Я создаю веб-сервис по примеру "Разработка веб-сервисов с Apache Axis2". Я использую ось 1.6.2 с rampart 1.6.2. Когда я выполняю клиент, я получаю следующее исключение:

Exception in thread "main" java.lang.RuntimeException: Undefined 'Security policy namespace cannot be null.' resource property
at org.apache.rampart.RampartException.getMessage(RampartException.java:81)
at org.apache.rampart.RampartException.<init>(RampartException.java:41)
at org.apache.rampart.RampartException.<init>(RampartException.java:57)
at org.apache.rampart.RampartMessageData.setWSSecurityVersions(RampartMessageData.java:387)
at org.apache.rampart.RampartMessageData.<init>(RampartMessageData.java:261)
at org.apache.rampart.MessageBuilder.build(MessageBuilder.java:61)
at org.apache.rampart.handler.RampartSender.invoke(RampartSender.java:65)
at org.apache.axis2.engine.Phase.invokeHandler(Phase.java:340)
at org.apache.axis2.engine.Phase.invoke(Phase.java:313)
at org.apache.axis2.engine.AxisEngine.invoke(AxisEngine.java:262)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:427)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at com.ttdev.secure.client.SecureServiceStub.concat(SecureServiceStub.java:188)
at com.ttdev.secure.client.SecureClient.main(SecureClient.java:51)

Это мой файл WSDL:

<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions name="SecureService" targetNamespace="http://ttdev.com/ss"         xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"         xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy"         xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://ttdev.com/ss"     xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <wsdl:types>
    <xsd:schema targetNamespace="http://ttdev.com/ss" xmlns:xsd="http://www.w3.org    /2001/XMLSchema">
            <xsd:element name="concat">
                <xsd:complexType>
                <xsd:sequence>
                    <xsd:element name="s1" type="xsd:string"/>
                    <xsd:element name="s2" type="xsd:string"/>
                </xsd:sequence>
            </xsd:complexType>
        </xsd:element>
        <xsd:element name="concatResponse">
            <xsd:complexType>
                <xsd:sequence>
                    <xsd:element name="r" type="xsd:string"/>
                </xsd:sequence>
            </xsd:complexType>
        </xsd:element>
    </xsd:schema>
  </wsdl:types>
  <wsdl:message name="concatResponse">
    <wsdl:part name="parameters" element="tns:concatResponse">
    </wsdl:part>
  </wsdl:message>
  <wsdl:message name="concatRequest">
    <wsdl:part name="parameters" element="tns:concat">
    </wsdl:part>
  </wsdl:message>
  <wsdl:portType name="SecureService">
    <wsdl:operation name="concat">
      <wsdl:input message="tns:concatRequest">
    </wsdl:input>
      <wsdl:output message="tns:concatResponse">
    </wsdl:output>
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="SecureServiceSOAP" type="tns:SecureService">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="concat">
    <wsp:PolicyReference URI="#p1" wsdl:required="true"/>
      <soap:operation soapAction="http://ttdev.com/ss/NewOperation"/>
      <wsdl:input>
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="SecureService">
    <wsdl:port name="SecureServiceSOAP" binding="tns:SecureServiceSOAP">
      <soap:address location="http://localhost:8081/axis2/services/SecureService"/>
    </wsdl:port>
  </wsdl:service>
    <wsp:Policy wsu:Id="p1" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"     xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-            wss-wssecurity-utility-1.0.xsd">
        <sp:AsymmetricBinding>
            <wsp:Policy>

                <sp:InitiatorToken>
                    <wsp:Policy>
                        <sp:X509Token     sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken    /AlwaysToRecipient">
                            <wsp:Policy>
                                <sp:WssX509V3Token10/>
                            </wsp:Policy>
                        </sp:X509Token>
                    </wsp:Policy>
                </sp:InitiatorToken>
                <sp:RecipientToken>
                    <wsp:Policy>
                        <sp:X509Token         sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                            <wsp:Policy>
                                <sp:WssX509V3Token10/>
                            </wsp:Policy>
                        </sp:X509Token>
                    </wsp:Policy>
                </sp:RecipientToken>
                <sp:AlgorithmSuite>
                    <wsp:Policy>
                        <sp:TripleDesRsa15/>
                    </wsp:Policy>
                </sp:AlgorithmSuite>
            </wsp:Policy>
        </sp:AsymmetricBinding>
        <sp:Wss10>
            <wsp:Policy>
                <sp:MustSupportRefEmbeddedToken/>
                <sp:MustSupportRefIssuerSerial/>
            </wsp:Policy>
        </sp:Wss10>
        <sp:SignedParts>
            <sp:Body/>
        </sp:SignedParts>

    </wsp:Policy>
</wsdl:definitions>

Это мой файл политики:

<?xml version="1.0" encoding="UTF-8"?>
<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" 
xmlns="http://ws.apache.org/rampart/policy">
    <RampartConfig>
        <user>c1</user>
        <passwordCallbackClass>
com.ttdev.secure.client.PasswordCallbackHandler
</passwordCallbackClass>
        <signatureCrypto>
            <crypto 
provider="org.apache.ws.security.components.crypto.Merlin">
                <property 
name="org.apache.ws.security.crypto.merlin.keystore.type">
JKS
</property>
                <property 
name="org.apache.ws.security.crypto.merlin.file">
E:\\Temp\\OK_Axis2Development\\keys\\client.ks
</property>
                <property 
name="org.apache.ws.security.crypto.merlin.keystore.password">
client-ks-pass
</property>
            </crypto>
        </signatureCrypto>
    </RampartConfig>
</wsp:Policy>

Это мой первый пост здесь, я надеюсь, что информации будет достаточно.

Согласно книге, в этом пункте, если я выполню клиент, я должен получить ошибку, потому что есть больше конфигурации для завершения примера, но по крайней мере я должен видеть мыльный xml, отправленный на сервер с монитором tcp.

Я не могу найти ответы, на этом сайте есть другие темы с тем же вопросом, но они не имеют ответов.

Наконец, это был клиентский код, я точно не знаю, почему, но я полагаю, что это проблема с версиями.

package com.ttdev.secure.client;

import java.io.FileNotFoundException;
import java.rmi.RemoteException;
import java.util.List;

import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.description.PolicyInclude;
import org.apache.neethi.Assertion;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.rampart.RampartMessageData;

public class SecureClient {

    public static void main(String[] args) {

        try {

            ConfigurationContext ctx = ConfigurationContextFactory
                    .createConfigurationContextFromFileSystem(
                            "repository\\modules\\rampart-1.6.2.mar",
                            null);

            SecureServiceStub stub = new SecureServiceStub(ctx,"http://localhost:9000/axis2/services/SecureService");

            stub._getServiceClient().engageModule("rampart");

            StAXOMBuilder builder = new StAXOMBuilder("rampart-config.xml");
            OMElement configElement = builder.getDocumentElement();
            Policy rampartConfig = PolicyEngine.getPolicy(configElement);


            //stub._getServiceClient().getOptions().setProperty(RampartMessageData.KEY_RAMPART_POLICY, rampartConfig); <= NO LONGER USED

            stub._getServiceClient().getAxisService().getPolicyInclude().addPolicyElement(PolicyInclude.AXIS_SERVICE_POLICY, rampartConfig);
            //stub._getServiceClient().getAxisService().getPolicyInclude().addPolicyElement(PolicyInclude.SERVICE_POLICY, rampartConfig);   <= IT IS USED IN THE BOOK
            //stub._getServiceClient().getAxisService().getPolicySubject().attachPolicy(rampartConfig); <= IT IS ANOTHER WAY TO ADD POLICIES IN THIS VERSION, TRY IT

//           List it = (List)rampartConfig.getAlternatives().next();
//            for (int i=0; i<it.size(); i++) {
//              Assertion assertion = (Assertion)it.get(i);
//              System.out.format("i: %s  |  type: %s  |  name: %s  |  namespace uri: %s", i, assertion.getClass().getName(), assertion.getName(), assertion.getName().getNamespaceURI());
//            }
//           System.out.println("\n");
//          
            //stub._getServiceClient().getAxisService().getPolicyInclude().addPolicyElement(PolicyInclude.SERVICE_POLICY,rampartConfig);
            //stub._getServiceClient().getAxisService().getPolicySubject().attachPolicy(rampartConfig);

            String result = stub.concat("xyz", "111");

            System.out.println(result);

        } catch (AxisFault e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (XMLStreamException e) {
            e.printStackTrace();
        }
    }
}

С уважением

1 ответ

У меня была ошибка на стороне клиента:

Я изменил эту строку:

stub._getServiceClient().getOptions().setProperty(RampartMessageData.KEY_RAMPART_POLICY, rampartConfig); 

этим: stub._getServiceClient().getAxisService().getPolicyInclude().addPolicyElement(PolicyInclude.AXIS_SERVICE_POLICY, rampartConfig);

Пример не завершен, но мне нужно было сначала решить эту проблему.

В моем случае я использовал мыльный интерфейс для создания ws-клиента для использования защищенного веб-сервиса. Я использовал WSDL, предоставленный моим провайдером. Когда мои классы (и мой jar) генерируются, все выполняется, но когда он достигает кода, который прикрепил политику, возникает исключение.

Последнее, что я проверил, это wsdl, потому что мой провайдер очень осторожен с этим... но, к моему удивлению, пропустил раздел политики... и именно поэтому возникает исключение.

Итак, я настоятельно рекомендую проверить, что wsdl содержит раздел политики.

С уважением.

Другие вопросы по тегам