Spring 安全“转发:"指令无法转发到登录表单 [英] Spring security "forward:" directive can't forward to login form

查看:18
本文介绍了Spring 安全“转发:"指令无法转发到登录表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在用户创建其帐户后,我希望该用户自动登录.

After a user creates their account, I want to log that user on automatically.

我在 /postlogin 上有由 Springs 过滤器处理的标准表单登录.如果我转到 http://localhost/postlogin,它会尝试让我登录(失败,因为我没有包含 post 参数),但会进行正确的尝试.

I have standard form logins being handled by Springs filter on /postlogin. If I go to http://localhost/postlogin it attempts to log me in (fails because I didn't include the post parameters), but makes the proper attempt.

但是如果我想以编程方式登录用户并尝试从控制器返回:forward:/postlogin"我得到 404.

But if I want to log the user in programatically and I try to return from the controller: "forward:/postlogin" I get a 404.

我假设 forward: 指令没有通过过滤器,因此不会被 UsernamePasswordAuthenticationFilter 处理.

I assume the forward: directive is not passing through the filters, thus not getting handled by the UsernamePasswordAuthenticationFilter.

如何以编程方式手动诱导登录?我想在用户创建新帐户后执行此操作(他们应在完成注册后立即登录该帐户).

How do I manually induce a login programatically? I want to do this after the user creates a new account (they should be logged into that account immediately upon completion of the registration).

推荐答案

我误读了另一篇指南,意识到正确的处理方法如下:

I mis-read another piece of guidance and realized that the correct way of handling this is the following:

1) 在 SecurityContextHolder 上手动设置身份验证令牌

1) Manually set the Authentication token on SecurityContextHolder

    UsernamePasswordWithAttributesAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( loadUserByUsername(username), password, authorities );
    SecurityContextHolder.getContext().setAuthentication(authenticationToken);

2) 不要此时渲染页面或使用 forward: 指令.您必须使用 redirect: 指令.

2) Do Not render a page at this point or use the forward: directive. You must use the redirect: directive.

return "redirect:/accountcreated";

如果你渲染一个页面,页面会加载正常,但会话对象会丢失,因为一个新的 j_session_id 将被创建,但不会在浏览器中间请求并且下一个请求将使用旧的 j_session_id,丢失新的会话对象 &认证.

If you render a page the page will load fine, but the session object will be lost because a new j_session_id will be created but will not make it to the browser mid-request and the next request will use the old j_session_id, loosing the new session object & authetication.

使用 forward: 指令会绕过身份验证过滤器,不好.

Using the forward: directive will bypass the authentication filters, no good.

但重定向:导致更新的会话信息使其进入浏览器.

But redirect: causes the updated session information to make it to the browser.

这篇关于Spring 安全“转发:"指令无法转发到登录表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆