【问题标题】:Spring Security 3 RestTemplate POST to j_spring_security_checkSpring Security 3 RestTemplate POST 到 j_spring_security_check
【发布时间】:2011-11-26 05:07:46
【问题描述】:

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

提前致谢。

【问题讨论】:

    标签: spring rest spring-security resttemplate


    【解决方案1】:

    这似乎与another SO question 重复。不过,您可能以错误的方式处理此问题。通常,如果您发出 REST 请求,您不会同时进行身份验证 - 这没有任何意义 - 当然不使用表单 POST 样式逻辑。

    对于 REST 请求的身份验证,您应该使用另一种形式的身份验证(假设这些请求是以编程方式生成的): * HTTP 基本认证 * X.509 证书

    或者,如果这是通过 XHR / Javascript 来源发生的,您应该准备好让请求失败并将用户重定向到登录机制。通常使用 Spring Security 处理 REST 样式请求与处理常规安全页面完全不同。您应该为一定程度的复杂性做好准备。

    祝你好运!

    【讨论】:

    • 感谢您的回复,我确实看过其他帖子,也许我可以尝试采用他们的方法。我会看看 X.509,它可能运行良好。
    猜你喜欢
    • 1970-01-01
    • 2013-03-10
    • 2015-02-12
    • 2013-05-03
    • 2015-07-10
    • 2014-01-09
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    相关资源
    最近更新 更多