使用RestTemplate的Spring Security身份验证

我有2个Spring Web应用程序,它们提供2套独立的服务。Web App 1具有使用基于用户的身份验证实现的Spring Security。

现在,Web App 2需要访问Web App 1的服务。通常,我们将使用RestTemplate类向其他Web服务发出请求。

我们如何将Web App 2的请求中的身份验证凭据传递给Web App 1

回答:

我当时处在同样的情况。这是我的解决方案。

服务器-Spring Security配置

<sec:http>

<sec:intercept-url pattern="/**" access="ROLE_USER" method="POST"/>

<sec:intercept-url pattern="/**" filters="none" method="GET"/>

<sec:http-basic />

</sec:http>

<sec:authentication-manager alias="authenticationManager">

<sec:authentication-provider>

<sec:user-service>

<sec:user name="${rest.username}" password="${rest.password}" authorities="ROLE_USER"/>

</sec:user-service>

</sec:authentication-provider>

</sec:authentication-manager>

客户端 配置

<bean id="httpClient" class="org.apache.commons.httpclient.HttpClient">

<constructor-arg ref="httpClientParams"/>

<property name="state" ref="httpState"/>

</bean>

<bean id="httpState" class="CustomHttpState">

<property name="credentials" ref="credentials"/>

</bean>

<bean id="credentials" class="org.apache.commons.httpclient.UsernamePasswordCredentials">

<constructor-arg value="${rest.username}"/>

<constructor-arg value="${rest.password}"/>

</bean>

<bean id="httpClientFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory">

<constructor-arg ref="httpClient"/>

</bean>

<bean class="org.springframework.web.client.RestTemplate">

<constructor-arg ref="httpClientFactory"/>

</bean>

自定义HttpState实现

/**

* Custom implementation of {@link HttpState} with credentials property.

*

* @author banterCZ

*/

public class CustomHttpState extends HttpState {

/**

* Set credentials property.

*

* @param credentials

* @see #setCredentials(org.apache.commons.httpclient.auth.AuthScope, org.apache.commons.httpclient.Credentials)

*/

public void setCredentials(final Credentials credentials) {

super.setCredentials(AuthScope.ANY, credentials);

}

}

Maven依赖

<dependency>

<groupId>commons-httpclient</groupId>

<artifactId>commons-httpclient</artifactId>

<version>3.1</version>

</dependency>

以上是 使用RestTemplate的Spring Security身份验证 的全部内容, 来源链接: utcz.com/qa/405813.html

回到顶部