加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 使用RestTemplate的Spring Security身份验证

发布时间:2020-12-15 00:24:39 所属栏目:Java 来源:网络整理
导读:我有2个 Spring Web应用程序,提供2个单独的服务. Web App 1具有使用基于用户身份验证的Spring Security实现. 现在,Web App 2需要访问Web App 1的服务.通常,我们将使用RestTemplate类向其他Web服务发出请求. 我们如何将Web App 2的请求中的认证凭证传递给Web
我有2个 Spring Web应用程序,提供2个单独的服务. Web App 1具有使用基于用户身份验证的Spring Security实现.

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

我们如何将Web App 2的请求中的认证凭证传递给Web App 1

解决方法

我处于同样的境地.这里有我的解决方案

服务器 – 弹簧安全配置

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读