使用RestTemplate Spring Security认证 [英] Spring Security Authentication using RestTemplate

查看:578
本文介绍了使用RestTemplate Spring Security认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个春天的Web应用程序提供2组独立的服务。 Web应用程序1有春季安全使用一个基于用户的认证来实现。

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应用程序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.

我们如何通过身份验证凭据在网络的应用程序2请求Web应用程序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.

服务器 - 春季安全配置

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的依赖

Maven dependency

<dependency>
   <groupId>commons-httpclient</groupId>
   <artifactId>commons-httpclient</artifactId>
   <version>3.1</version>
</dependency>

这篇关于使用RestTemplate Spring Security认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆