【问题标题】:Is it possible to programmatically authenticate with Spring Security and make it persistent?是否可以通过 Spring Security 以编程方式进行身份验证并使其持久化?
【发布时间】:2011-07-02 12:13:27
【问题描述】:

我在 Spring Controller 中使用以下方法来允许通过 Ajax 进行身份验证。它可以工作,但它似乎没有创建 cookie 或任何使身份验证持久的东西。

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public LoginStatus login(@RequestParam("j_username") String username,
                         @RequestParam("j_password") String password) {

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);

    try {
        Authentication auth = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(auth);
        return new LoginStatus(auth.isAuthenticated(), auth.getName());
    } catch (BadCredentialsException e) {
        return new LoginStatus(false, null);
    }
}

我需要做什么才能使身份验证持久化?

【问题讨论】:

标签: java security spring spring-security


【解决方案1】:

确定

  • 您已配置SecurityContextPersistenceFilter
  • 您没有将<security:http> 标记的create-session 属性设置为none

【讨论】:

  • 我尝试查看 SecurityContextPersistenceFilter 中的逻辑并复制它。我添加了对 SecurityContextRepository 的引用,并在验证用户身份后尝试调用其 saveContext() 方法。还是没有骰子。
  • 以标准方式配置 Spring Security 过滤器链比模仿它更容易吗?顺便说一句,请注意SecurityContextPersistenceFilter javadoc:必须在任何身份验证处理机制之前执行此过滤器。身份验证处理机制(例如 BASIC、CAS 处理过滤器等)期望 SecurityContextHolder 在执行时包含有效的 SecurityContext。这意味着上下文创建和存储应该发生在之前执行身份验证。
  • 我已经成功地使用这种技术与 j_security_check 对话,并让它像 LoginService 实现一样工作。但是,我仍然面临着让 HTTPS 登录持续到 HTTP 的相同问题。我在 GitHub 项目中创建了一个 j_security_check 分支来尝试让这个替代实现工作。 github.com/mraible/ajax-login/tree/j_security_check
猜你喜欢
  • 2017-09-01
  • 2016-05-11
  • 2012-03-06
  • 2013-02-23
  • 2014-08-13
  • 2019-03-07
  • 1970-01-01
  • 2013-08-03
  • 2013-06-12
相关资源
最近更新 更多