用户创建帐户后,我想自动让该用户登录。
/poSTLogin
上的 Springs 过滤器正在处理标准表单登录。如果我转到 http://localhost/poSTLogin
,它会尝试让我登录(失败,因为我没有包含 post 参数),但会进行正确的尝试。
但是如果我想以编程方式让用户登录并尝试从 Controller 返回:“forward:/poSTLogin”,我会收到 404。
我假设 forward: 指令没有通过过滤器,因此没有被 UsernamePasswordAuthenticationFilter
处理。
如何以编程方式手动诱导登录?我想在用户创建新帐户后执行此操作(他们应在完成注册后立即登录到该帐户)。
最佳答案
我误读了另一篇指南,并意识到正确的处理方法如下:
1) 在 SecurityContextHolder 上手动设置身份验证 token
UsernamePasswordWithAttributesAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( loadUserByUsername(username), password, authorities );
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
2) 不要此时呈现页面或使用 forward: 指令。您必须使用重定向:指令。
return "redirect:/accountcreated";
如果你呈现一个页面,页面将加载正常,但 session 对象将丢失,因为一个新的 j_session_id 将被创建,但不会在请求中到达浏览器,下一个请求将使用旧的 j_session_id,丢失新的 session 对象和身份验证。
使用 forward: 指令将绕过身份验证过滤器,这不好。
但是重定向:导致更新的 session 信息到达浏览器。
关于java - Spring Security "forward:"指令无法转发到登录表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4824395/