如何使用Spring Security保护REST Web服务

时间:2017-02-22 17:57:16

标签: spring web-services rest spring-security

我正在尝试在url / dispatcher / rest / **

保护我的REST Web服务

如果通过浏览器访问Web服务,我当前的设计工作正常 - 当我尝试转到REST URL时,它会将我重定向到登录页面以输入凭据,然后在登录后将我重定向到Web服务数据。

问题是,当我尝试使用RestTemplate通过java代码访问Web服务时,我的代码中断了。即使用户已经登录并进行了身份验证,也会发生这种情况。

我的spring-security.xml配置文件:

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <!-- enable use-expressions -->
    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/dispatcher/admin**" access="hasRole('ROLE_ADMIN')" />
 <intercept-url pattern="/dispatcher/rest/**" access="hasRole('ROLE_ADMIN')"/>
        <!-- access denied page -->
        <access-denied-handler error-page="/dispatcher/403" />
        <form-login 

            login-page="/dispatcher/login" 
            default-target-url="/dispatcher/admin"
            login-processing-url="/dispatcher/login_process"
            authentication-failure-url="/dispatcher/login?error" 
            username-parameter="username"
            password-parameter="password" />
        <logout logout-success-url="/dispatcher/login?logout" logout-url = "/dispatcher/logout"/>
        <!-- enable csrf protection -->
        <csrf />
        </http>

    <authentication-manager>
        <authentication-provider user-service-ref="myUserDetailsService" >

        </authentication-provider>
    </authentication-manager>
<beans:bean id="myUserDetailsService" class="com.shopping.services.MyUserDetailsService" />
</beans:beans>

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我发现访问Web服务的解决方案如下:

 String username = ((UserDetails) principal).getUsername();
         String password = ((UserDetails) principal).getPassword();
        HttpClient client = new HttpClient();
        client.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        restTemplate.setRequestFactory(new CommonsClientHttpRequestFactory(client));
        client.getState().setCredentials(AuthScope.ANY, defaultcreds);
        User x = restTemplate.getForObject("http://localhost:8080/Online_Shopping/dispatcher/rest/hello",User.class);