我试图在URL/dispatcher/rest/**
上保护我的REST Web服务如果通过浏览器访问Web服务,我的当前设计正常工作 - 当我尝试使用其余网址时,它将我重定向到登录页面以输入凭据,然后将我重定向到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>
任何帮助将不胜感激!
我发现访问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);