0

我正在使用带有 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 之外,还有更好的登录/获得授权方式吗?信息是否在标题中?

提前致谢。

4

1 回答 1

1

This seems like a duplicate of another SO question. You are probably approaching this the wrong way, though. Typically if you are issuing a REST request you wouldn't be authenticating at the same time - this doesn't make any sense - certainly not using form POST style logic.

For authentication of REST requests you should be using another form of authentication (assuming these requests are generated programmatically): * HTTP Basic auth * X.509 certificates

OR if this is happening through an XHR / Javascript origin, you should be prepared to have the request fail and redirect the user to the login mechanism. Typically handling REST style requests with Spring Security is not at all the same as handling regular secured pages. You should be prepared for some amount of complexity.

Good luck!

于 2011-09-27T18:36:55.627 回答