2015-08-09 7 views
1

Мой случай выглядит следующим образом:Spring-WS Wss4jSecurityInterceptor не расшифровывает получил сообщение

  1. Я написал службы SOAP с помощью CXF
  2. Я написал два SOAP клиентов - один с помощью CXF, а другой с помощью Spring-WS
  3. Я установил WSSecurity: действие «Подпись подписи тайм-копии» с обеих сторон (клиент/сервер)
  4. Клиент CXF работает как шарм, но Spring-WS can not decrypt response.

Серверная сторона в порядке, взаимодействуя с CXF-клиентом и Spring-клиентом (она дешифрует, проверяет подпись, обрабатывает запросы, подписывает, шифрует и передает финналию ответ).

Код:

CXF клиент:


<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation=" 
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> 

<bean id="inbound-logging" class="org.apache.cxf.interceptor.LoggingInInterceptor" /> 
<bean id="outbound-logging" class="org.apache.cxf.interceptor.LoggingOutInterceptor" /> 

<jaxws:client id="helloClient" serviceClass="com.example.HelloWorld" 
    address="http://localhost:8282/HelloWorld"> 
    <jaxws:inInterceptors> 
     <ref bean="inbound-logging" /> 
     <ref bean="inbound-security" /> 
    </jaxws:inInterceptors> 
    <jaxws:outInterceptors> 
     <ref bean="outbound-logging" /> 
     <ref bean="outbound-security" /> 
    </jaxws:outInterceptors> 
</jaxws:client> 

<bean class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor" id="outbound-security"> 
    <constructor-arg> 
     <map> 
      <entry key="action" value="Timestamp Signature Encrypt"/> 
      <entry key="user" value="client"/>    
      <entry key="signaturePropFile" value="config/client-crypto.properties"/> 
      <entry key="encryptionPropFile" value="config/client-crypto.properties"/> 
      <entry key="signatureKeyIdentifier" value="DirectReference"/> 
      <entry key="encryptionUser" value="server"/> 
      <entry key="passwordCallbackClass" value="org.mydomain.ClientPasswordCallback"/> 
      <entry key="signatureParts" value="{Element}{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd}Timestamp;{Element}{http://schemas.xmlsoap.org/soap/envelope/}Body"/> 
      <entry key="encryptionParts" value="{Element}{http://www.w3.org/2000/09/xmldsig#}Signature;{Content}{http://schemas.xmlsoap.org/soap/envelope/}Body"/> 
      <entry key="encryptionSymAlgorithm" value="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/> 
     </map> 
    </constructor-arg> 
</bean> 

<bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor" id="inbound-security"> 
    <constructor-arg> 
     <map> 
      <entry key="action" value="Timestamp Signature Encrypt"/> 
      <entry key="signaturePropFile" value="config/client-crypto.properties"/> 
      <entry key="decryptionPropFile" value="config/client-crypto.properties"/> 
      <entry key="passwordCallbackClass" value="org.mydomain.CustomPasswordCallback"/> 
     </map> 
    </constructor-arg> 
</bean> 


Spring-WS клиент - WSS-перехватчик:


@Bean 
public Wss4jSecurityInterceptor wssInterceptor(
     @Qualifier("cryptoFactoryBean") CryptoFactoryBean cryptoFactoryBean, 
     @Qualifier("signValidCryptoFactoryBean") CryptoFactoryBean signValidCryptoFactoryBean) throws Exception { 

    Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); 

    // outgoing securement 

    interceptor.setSecurementUsername("client"); 
    interceptor.setSecurementPassword("123456"); 
    interceptor.setSecurementSignatureKeyIdentifier("DirectReference"); 
    interceptor.setSecurementActions("Timestamp Signature Encrypt"); 

    interceptor.setSecurementSignatureCrypto(cryptoFactoryBean.getObject()); 
    interceptor.setSecurementSignatureParts(
      "{Element}{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd}Timestamp;" + 
      "{Element}{http://schemas.xmlsoap.org/soap/envelope/}Body" 
    ); 

    interceptor.setSecurementEncryptionCrypto(cryptoFactoryBean.getObject()); 
    interceptor.setSecurementEncryptionUser("server"); 
    interceptor.setSecurementEncryptionSymAlgorithm("http://www.w3.org/2001/04/xmlenc#tripledes-cbc"); 
    interceptor.setSecurementEncryptionParts(
      "{Element}{http://www.w3.org/2000/09/xmldsig#}Signature;" + 
      "{Content}{http://schemas.xmlsoap.org/soap/envelope/}Body" 
    ); 

    // incoming validation: 

    interceptor.setValidationActions("Timestamp Signature Encrypt"); 
    interceptor.setValidationDecryptionCrypto(cryptoFactoryBean.getObject()); 
    interceptor.setValidationSignatureCrypto(signValidCryptoFactoryBean.getObject()); 

    return interceptor; 
} 

Уровень ведения журнала установлен на отладку. Вот результат:


(... - журналы, связанные с шифрованием данных befrore посыла) 2015-08-09 19: 09: 45,181 DEBUG WSSecEncrypt: 258 - Шифрование завершено. 2015-08-09 19: 09: 45,182 DEBUG отправлено: 620 - Отправлен запрос [SaajSoapMessage {http://www.w3.org/2001/04/xmlenc#} EncryptedData] 2015-08-09 19: 09: 45,223 DEBUG получил: 678 - Получен ответ [SaajSoapMessage {http://www.w3.org/2001/04/xmlenc#} EncryptedData] для запроса [SaajSoapMessage {http://www.w3.org/2001/04/xmlenc#} EncryptedData] 2015-08-09 19: 09: 45,224 DEBUG Wss4jSecurityInterceptor: 562 - Проверка сообщения [SaajSoapMessage {http://www.w3.org/2001/04/xmlenc#} EncryptedData] с действиями [Отметка Подпись Шифрование] 2015-08-09 19 : 09: 45.225 DEBUG WSSecurityEngine: 236 - введите processSecurityHeader() 2015-08-09 19: 09: 45.229 WARN Wss4jSecurityInterceptor: 281 - Не удалось проверить запрос: нет заголовка WS-Security 2015-08-09 19: 09: 45.229 DEBUG Wss4jSecurityInterceptor: 288 - Репрезентатор ошибки отсутствует, создавая основную ошибку мыла Исключение в потоке «main» org.springframework.oxm.UnmarshallingFailureException: исключение JAXB unmarshalling; Вложенное исключение - javax.xml.bind.UnmarshalException: неожиданный элемент (uri: «http://schemas.xmlsoap.org/soap/envelope/», local: «Fault»). Ожидаемые элементы < {} helloRequest>, < {} http://example.com helloResponse> в org.springframework.oxm.jaxb.Jaxb2Marshaller.convertJaxbException (Jaxb2Marshaller.java:809) в org.springframework.oxm.jaxb.Jaxb2Marshaller.unmarshal (Jaxb2Marshaller .java: 730) в org.springframework.ws.support.MarshallingUtils.unmarshal (MarshallingUtils.java:62) в org.springframework.ws.client.core.WebServiceTemplate $ 3.extractData (WebServiceTemplate.java:407) в org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive (WebServiceTemplate.java:596) на org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive (WebServiceTemplate.java:537) в org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive (WebServiceTemplate. Java: 384) на org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive (WebServiceTemplate.java:374) на client.Main.main (Main.java:39) в sun.reflect.NativeMethodAccessorImpl.invoke0 (Родной метод) на sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) на sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) в java.lang.reflect.Method.invoke (Method.java : 497) по адресу: com.intellij.rt.execution.application.AppMain.main (AppMain.java:134) Вызвано: javax.xml.bind.UnmarshalException: неожиданный элемент (uri: «http://schemas.xmlsoap.org/soap/envelope/», local: «Fault»). Ожидаемые элементы < {} helloRequest>, < {} http://example.com helloResponse> в com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent (UnmarshallingContext.java:726) на com.sun.xml .internal.bind.v2.runtime.unmarshaller.Loader.reportError (Loader.java:247) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError (Loader.java:242) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement (Loader.java:109) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext $ DefaultRootLoader.childElement (UnmarshallingContext.java:1131) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement (UnmarshallingContext.java:556) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement (UnmarshallingContext.java:538) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement (InterningXmlVisitor.java:60) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement (SAXConnector.java:153) at com.sun.xml.internal.bind.unmarshaller.DOMScanner. посетите (DOMScanner.java:229) по адресу com.sun.xml.internal.bind.unmarshaller.DOMScanner.scan (DOMScanner.java:112) по адресу com.sun.xml.internal.bind.v2.runtime.unmarshaller. UnmarshallerImpl.unmarshal0 (UnmarshallerImpl.java:354) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal (UnmarshallerImpl.java:337) at javax.xml.bind.helpers.Abstract UnmarshallerImpl.unmarshal (AbstractUnmarshallerImpl.java:127) в org.springframework.oxm.jaxb.Jaxb2Marshaller.unmarshal (Jaxb2Marshaller.java:726) ... 12 более


Похоже, весна пытается ответ процесса без дешифрования ранее.


Я нашел решение проблемы. Я не устанавливал обратный вызов пароля, поэтому wss4j-перехватчик не мог расшифровать ответ. Вот код, который исправить проблему:

KeyStoreCallbackHandler keyStoreCallbackHandler = new KeyStoreCallbackHandler(); 
keyStoreCallbackHandler.setPrivateKeyPassword("123456"); 
interceptor.setValidationCallbackHandler(keyStoreCallbackHandler); 
+0

Я также сталкиваюсь с той же проблемой. Где я должен добавить этот фрагмент? В CallbackHandler или нужно создать новый класс и добавить его в файл cfg? Пожалуйста помоги –

ответ

0

KeyStoreCallbackHandler не был определен для перехватчика - так было. Соответствующий код в начальном посте.

0

Вы получаете потерю мыла от другой стороны. Сообщения о неисправностях мыла не зашифрованы, поэтому Wss4jSecurityInterceptor жалуется на заголовок ws-security.

2015-08-09 19:09:45.229 WARN Wss4jSecurityInterceptor:281 - 
**Could not validate request: No WS-Security header found** 

Похоже, что обработка сообщения продолжается, пока он нормализуется.Маршаллер JAXB жалуется, что (uri: «http://schemas.xmlsoap.org/soap/envelope/», local: «Fault») не из контекста.

2015-08-09 19:09:45.229 DEBUG Wss4jSecurityInterceptor:288 - 
No exception resolver present, creating basic soap fault 
Exception in thread "main" 
org.springframework.oxm.UnmarshallingFailureException: 
JAXB unmarshalling exception; nested exception is 
javax.xml.bind.UnmarshalException: unexpected element 
(uri:"http://schemas.xmlsoap.org/soap/envelope/", local:"Fault"). 
Expected elements are <{}helloRequest>,<{http://example.com}helloResponse> 

Я бы рекомендовал следующее:

  1. Вход вина мыло, чтобы определить, что другая сторона нуждается в
  2. Всякий раз, когда вы получите ошибку мыло, вы должны прекратить обработку запроса