使用 RestTemplate 的 Spring Security 身份验证 [英] Spring Security Authentication using RestTemplate
问题描述
我有 2 个 Spring Web 应用程序,它们提供 2 组独立的服务.Web App 1 使用基于用户的身份验证实现了 Spring Security.
I have 2 spring web apps that provide 2 separate set of services. Web App 1 has Spring Security implemented using a user-based authentication.
现在,Web App 2 需要访问Web App 1 的服务.通常,我们会使用RestTemplate 类向其他Web 服务发出请求.
Now, Web App 2 needs to access the service of Web App 1. Normally, we would use the RestTemplate class to make requests to other web services.
我们如何将 Web App 2 请求中的身份验证凭据传递给 Web App 1
How do we pass the authentication credentials in the request of Web App 2 to Web App 1
推荐答案
我遇到了同样的情况.这是我的解决方案.
I was in the same situation. Here there is my solution.
服务器 - spring 安全配置
Server - spring security config
<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>
客户端RestTemplate配置
<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 HttpState implementation
/**
* 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 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!