代码之家  ›  专栏  ›  技术社区  ›  Kris Swat

抢先身份验证-httpcomponentsMessagesender

  •  0
  • Kris Swat  · 技术社区  · 6 年前

    如何在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 回复  |  直到 6 年前
        1
  •  1
  •   Artem Bilan    6 年前

    你需要注入一个定制的 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;
    }
    

    因此,对于抢先认证,我们需要扩展 http组件消息发送程序 并实现该方法以提供 context 就像ApacheCommons文档中显示的那样:

    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;
    }
    

    当然,这个 语境 必须在实例级别缓存,以便将来在每个实例级别中重用 httpclient.execute() .