[英]Avoid double authentication when using custom bean spring security
I have a login form that calls a certain LoginBean
, which returns a ajax callback parameter indicating whether the credentials are valid or not. 我有一个登录表单,该表单调用某个LoginBean
,该表单返回一个ajax回调参数,该参数指示凭据是否有效。 The code is as follows: 代码如下:
public void doLogin() {
Authentication authenticationRequestToken =
new UsernamePasswordAuthenticationToken(user, password);
try {
Authentication authenticationResponseToken =
authenticationManager.authenticate(authenticationRequestToken);
SecurityContextHolder.getContext().
setAuthentication(authenticationResponseToken);
if (authenticationResponseToken.isAuthenticated()) {
RequestContext context = RequestContext.getCurrentInstance();
FacesMessage msg;
boolean loggedIn = true;
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", user);
FacesContext.getCurrentInstance().addMessage(null, msg);
context.addCallbackParam("loggedIn", loggedIn);
}
} .authenticate(...) catches ...
// Here I need some code that continue whatever j_spring_security_check
// would do after authenticating.
}
The way my application is working now, after this call to doLogin()
, the form is submited to j_spring_security_check
, and then the authentication process takes place again, wasting previous work. 在调用doLogin()
之后,我的应用程序现在的工作方式是将表单提交给j_spring_security_check
,然后再次进行身份验证过程,这浪费了以前的工作。 I'm trying to find a solution for this, any help is appreciated. 我正在尝试为此找到解决方案,我们将不胜感激。
So, the bottom line is that I need something that would simulate what happens when j_spring_security_check
is intercepted by the filters (or a way to force this interception explicitly), so the processing would take place behind the button, not after the form is submited. 因此,最重要的是我需要一些东西来模拟过滤器拦截j_spring_security_check
时发生的情况(或明确强制这种拦截的方法),因此处理将在按钮后面进行,而不是在提交表单之后进行。
It will be better if you just forward to the spring security authentication url instead of using the SecurityContextHolder
yourself. 如果只转发到spring安全身份验证URL,而不是自己使用SecurityContextHolder
那会更好。 Look at this code: 看下面的代码:
public String doLogin() throws ServletException, IOException {
FacesContext context = FacesContext.getCurrentInstance();
String springCheckUrl = this.buildSpringSecurityCheckUrl();
HttpServletRequest request = (HttpServletRequest) context
.getExternalContext().getRequest();
RequestDispatcher dispatcher = request
.getRequestDispatcher(springCheckUrl);
dispatcher.forward((ServletRequest) request,
(ServletResponse) context.getExternalContext.getResponse());
context.responseComplete();
return null;
}
private String buildSpringSecurityCheckUrl() {
StringBuilder springCheckUrl = new StringBuilder(
"/j_spring_security_check").append("?").append("j_username")
.append("=").append(this.userName.trim()).append("&")
.append("j_password").append("=")
.append(this.userPassword.trim());
return springCheckUrl.toString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.