Шаблон веб-службы Spring: добавление токена имени пользователя - PullRequest
3 голосов
/ 15 февраля 2012

У меня есть веб-приложение, которое действует как клиент для веб-службы Jax-WS, реализованной с использованием Spring WS.Spring WS настроен на требование токена имени пользователя в заголовке SOAP.В веб-приложении я планирую использовать шаблон веб-службы Spring, но не могу найти примеров, показывающих, как добавить UsernameToken к исходящему запросу.

Может ли кто-нибудь указать мне правильное направление?

Спасибо.

Ответы [ 3 ]

11 голосов
/ 15 февраля 2012

Вы должны использовать Перехватчики . См. Глава 7. Защита ваших веб-сервисов с помощью Spring-WS .

.

Конфигурация будет выглядеть примерно так

<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
    <property name="marshaller" ref="marshaller" />
    <property name="unmarshaller" ref="marshaller" />
    <property name="defaultUri"
        value="http://localhost:8080/ws-demo/myws" />
    <property name="interceptors">
        <list>
            <ref bean="wsSecurityInterceptor" />
        </list>
    </property>
</bean>

<bean id="wsSecurityInterceptor" class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
    <property name="securementActions" value="UsernameToken"/>
    <property name="securementUsername" value="Ernie"/>
    <property name="securementPassword" value="Bert"/>
</bean>
2 голосов
/ 30 сентября 2018

Вышеуказанный ответ используется для xml.

Я упоминаю здесь базовую конфигурацию аннотации для политики безопасности usernameToken для веб-службы.

Добавьте эту конфигурацию с клиентом весенней загрузки

@Bean
public WebServiceTemplate webServiceTemplate() {
    WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
    webServiceTemplate.setMarshaller(marshaller());
    webServiceTemplate.setUnmarshaller(marshaller());
    webServiceTemplate.setDefaultUri("http://localhost:8080/ws");
    webServiceTemplate.setInterceptors(new ClientInterceptor[] {wsSecurityInterceptor()}); 
    return webServiceTemplate;
}

@Bean
public Wss4jSecurityInterceptor wsSecurityInterceptor() {
    Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
    wss4jSecurityInterceptor.setSecurementActions(WSHandlerConstants.TIMESTAMP + " " + WSHandlerConstants.USERNAME_TOKEN);
    wss4jSecurityInterceptor.setSecurementPasswordType(WSConstants.PW_TEXT);
    wss4jSecurityInterceptor.setSecurementUsername("user");
    wss4jSecurityInterceptor.setSecurementPassword("password");
    return wss4jSecurityInterceptor;
}   
2 голосов
/ 15 февраля 2012

в дополнение к ответу jddsantaella клиентский класс может использовать SAAJ для добавления токена имени пользователя в заголовок SOAP:

OrganisationPortfolioRequest request = WS_CLIENT_FACTORY.createOrganisationsPortfolioRequest();
OrganisationPortfolioResponse response;

response = (OrganisationPortfolioResponse) webServiceTemplate.marshalSendAndReceive(request, 
            new WebServiceMessageCallback() {
        public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
            SaajSoapMessage soapMessage = (SaajSoapMessage) message;
            SoapEnvelope envelope = soapMessage.getEnvelope();
            envelope.addNamespaceDeclaration("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
            envelope.addNamespaceDeclaration("s", "http://company.com/ws/security.xsd");

            SoapHeaderElement username =  soapMessage.getSoapHeader().addHeaderElement(new QName("http://company.com/ws/security.xsd", "username", "s"));
            username.setText(getCurrentUser.getUsername());
        }
    });
response.getResults();
...