为oauthRestTemplate注入自定义请求工厂

时间:2016-03-16 04:40:35

标签: spring spring-integration

我正在注入我的休息模板,如下所示。我想要SSL以及连接池和我自己的消息转换器。我正在使用以下配置

import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.net.ssl.SSLContext;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

    public class CustomRestTemplate  extends RestTemplate{

         private static final Logger LOGGER = LoggerFactory
                    .getLogger(RestTemplate.class);


        public CustomRestTemplate()  {
             super(createBatchHttpRequestFactory());
            List<HttpMessageConverter<?>> messageConverters= new ArrayList<HttpMessageConverter<?>>();
            messageConverters.addAll(getMessageConverters());
            messageConverters.add(0,new StringHttpMessageConverter(Charset.forName("UTF-8")));
            setMessageConverters(messageConverters);

        }

        private static ClientHttpRequestFactory createBatchHttpRequestFactory()  {

                CloseableHttpClient httpClient;
                HttpComponentsClientHttpRequestFactory httpRequestFactory;
                final int timeout = 3000;
                SSLConnectionSocketFactory socketFactory;
                try {
                    socketFactory = new SSLConnectionSocketFactory(
                            SSLContext.getDefault(),
                            new String[] {"TLSv1"},
                            null,
                            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", socketFactory)
                        .build();
                PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
                cm.setMaxTotal(3000);
                cm.setDefaultMaxPerRoute(1000);
                cm.closeExpiredConnections();


                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                        .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();



                httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(cm).build();


                httpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
                return httpRequestFactory;

                }

                catch (Exception e) {
                     LOGGER.debug("error exception", e);


        }
                return null; 
        }

我的春天配置如下。

<int-http:outbound-gateway id='http-test'  header-mapper="headerMapper"
                               request-channel='testChannel'
                               rest-template="customRestTemplate"
                               url-expression="payload.contains('${filterAttribute}') ? '${url1}' : '${url2}'"  http-method="${httpMethod}"
                               expected-response-type='java.lang.String' charset='${charset}'
                               reply-timeout='${replyTimeout}' reply-channel='output'>
    </int-http:outbound-gateway>



     <beans:bean  id="customRestTemplate" class="com.test.CustomRestTemplate" >
       <beans:constructor-arg name="requestTimeOut" value="${requestTimeOut}"/>
        <beans:constructor-arg name="maxConnectionPerRoute" value="${maxConnectionPerRoute}"/>
        <beans:constructor-arg name="totalMaxConnections" value="${totalMaxConnections}"/>
</beans:bean>

我想为oauthrestTemplate创建一个类似的出站http网关,并为SSL和连接池注入我的httprequestfactory。我怎么能这样做。我不想复制org.springframework.security.oauth2.client.OAuth2RestTemplate并复制代码。如何注射?

    <int-http:outbound-gateway id='ouath-http'  header-mapper="headerMapper"
                                   request-channel='oauthChannel'
                                   rest-template="oAuthRestTemplate"
                                   url-expression="payload.contains('${filterAttribute}') ? '${url1}' : '${url2}'"  http-method="${httpMethod}"
                                   expected-response-type='java.lang.String' charset='${charset}'
                                   reply-timeout='${replyTimeout}' reply-channel='output'>
        </int-http:outbound-gateway>

<beans:bean id="oAuthRestTemplate" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
         <beans:constructor-arg ref="clientCredentialsResource"/>

    </beans:bean>

<beans:bean id= "clientCredentialsResource" class="test.CustomClientCredentialsResourceDetails">
        <beans:property name="clientId" value="${clientId}" />
        <beans:property name="clientSecret" value="#{clientSecret}}" />
        <beans:property name="accessTokenUri" value="${accessTokenUri}" />
    </beans:bean> 

1 个答案:

答案 0 :(得分:0)

我面临同样的问题,但请看:https://github.com/spring-projects/spring-security-oauth/issues/459,这是不可能的。您需要做的是将请求工厂注入访问提供程序。我使用了以下代码,希望你也能这样做:

private ClientHttpRequestFactory getRequestFactory() {
    return null;
}

private AccessTokenProvider getAccessTokenProvider() {
    AuthorizationCodeAccessTokenProvider authorizationCodeAccessTokenProvider = new AuthorizationCodeAccessTokenProvider();
    authorizationCodeAccessTokenProvider.setRequestFactory(getRequestFactory());
    ImplicitAccessTokenProvider implicitAccessTokenProvider = new ImplicitAccessTokenProvider();
    implicitAccessTokenProvider.setRequestFactory(getRequestFactory());
    ResourceOwnerPasswordAccessTokenProvider resourceOwnerPasswordAccessTokenProvider = new ResourceOwnerPasswordAccessTokenProvider();
    resourceOwnerPasswordAccessTokenProvider.setRequestFactory(getRequestFactory());
    ClientCredentialsAccessTokenProvider clientCredentialsAccessTokenProvider = new ClientCredentialsAccessTokenProvider();
    clientCredentialsAccessTokenProvider.setRequestFactory(getRequestFactory());
    AccessTokenProvider accessTokenProvider = new AccessTokenProviderChain(Arrays.<AccessTokenProvider>asList(
            authorizationCodeAccessTokenProvider
            , implicitAccessTokenProvider,
            resourceOwnerPasswordAccessTokenProvider, clientCredentialsAccessTokenProvider));

    return accessTokenProvider;
}

private OAuth2RestTemplate getOAuth2RestTemplate() {
    OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
    facebookTemplate.setAccessTokenProvider(getAccessTokenProvider());

    return facebookTemplate;
}