我正在使用带有REST端点的Spring Security 3。我设法获得了一个基本的Spring Security工作。
security-context.xml的一部分
<security:http auto-config="true" use-expressions="true" access-denied-page="/rest/denied" >
<security:intercept-url pattern="/rest/*" access="ROLE_USER"/>
和网络上的基本配置
<security:authentication-manager>
<security:authentication-provider user-service-ref="userDetailsService">
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
<!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database -->
<bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>
<!-- An in-memory list of users. No need to access an external database layer.
See Spring Security 3.1 Reference 5.2.1 In-Memory Authentication -->
<!-- john's password is admin, while jane;s password is user -->
<security:user-service id="userDetailsService">
<security:user name="john" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_USER, ROLE_ADMIN" />
<security:user name="jane" password="ee11cbb19052e40b07aac0ca060c23ee" authorities="ROLE_USER" />
</security:user-service>
我想使用RestTemplate POST登录j_spring_security_check。
HttpEntity<String> entity = new HttpEntity<String>(request, headers);
HashMap<String, String> map = new HashMap<String, String>();
map.put("j_username", "john");
map.put("j_password","21232f297a57a5a743894a0e4a801fc3");
String response = restTemplate.postForObject("http://localhost:8080/rest/j_spring_security_check", map, String.class);
但是在日志中,似乎没有读取用户名参数
DEBUG o.s.s.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
DEBUG o.s.s.a.d.DaoAuthenticationProvider - User '' not found
DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
让REST模板发布身份验证凭据的正确方法是什么?除了j_spring_security_check之外,还有更好的方法来登录/获得授权吗?信息是否在标题中?
提前致谢。
答案 0 :(得分:1)
这似乎是another SO question的副本。不过,你可能正以错误的方式接近这一点。通常,如果您发出REST请求,则不会同时进行身份验证 - 这没有任何意义 - 当然不使用表单POST样式逻辑。
对于REST请求的身份验证,您应该使用其他形式的身份验证(假设这些请求是以编程方式生成的): * HTTP Basic身份验证 * X.509证书
如果这是通过XHR / Javascript源发生的,您应该准备让请求失败并将用户重定向到登录机制。通常使用Spring Security处理REST样式请求与处理常规安全页面完全不同。你应该为一些复杂性做好准备。
祝你好运!