抢占式身份验证-HttpComponentsMessageSender

时间:2019-01-21 13:13:13

标签: spring-integration

如何在HttpComponentsMessageSender中启用抢占式身份验证

<bean id="httpComponentsMessageSender" class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
    <property name="credentials">
        <bean class="org.apache.http.auth.UsernamePasswordCredentials">
            <constructor-arg value="userName"/>
            <constructor-arg value="password"/>
        </bean>
    </property>
</bean>

错误:

<faultcode>soapenv:Server.Transport.Http.401</faultcode><faultstring>1136 The HTTP Webservice returned an error: HTTP/1.1 401 Unauthorized</faultstring>

1 个答案:

答案 0 :(得分:2)

您需要将自定义的HttpClient注入发件人。而且您可以根据官方Apache文档https://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

来实现该定制的客户端
  

HttpClient不开箱即用地支持抢占式身份验证,因为抢占式身份验证如果滥用或使用不当会导致严重的安全问题,例如将用户凭据以明文形式发送给未经授权的第三方。

更新

HttpComponentsMessageSender具有以下方法:

/**
 * Template method that allows for creation of a {@link HttpContext} for the given uri. Default implementation
 * returns {@code null}.
 *
 * @param uri the URI to create the context for
 * @return the context, or {@code null}
 */
protected HttpContext createContext(URI uri) {
    return null;
}

因此,对于抢先身份验证而言,我们需要扩展HttpComponentsMessageSender并实现该方法以提供必需的context,如Apache Commons文档中所示:

protected HttpContext createContext(URI uri) {
    HttpHost targetHost = new HttpHost("localhost", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
         new AuthScope(targetHost.getHostName(), targetHost.getPort()),
         new UsernamePasswordCredentials("username", "password"));

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);


    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}

当然,此context必须缓存在实例级别上,以便以后在每个httpclient.execute()中重用。