它已弃用:
/**
* @deprecated If you want to retain the username, cache it in a customized {@code AuthenticationFailureHandler}
*/
@Deprecated
public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";
所以你需要实现你自己的AuthenticationFailureHandler
.
我实现了 1)策略:(记住用户名可以包含一些在 URL 中不合适的字符!)
package some.package;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UsernameInURLAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
private String urlPrefix;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private String formUsernameKey = UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY;
public UsernameInURLAuthenticationFailureHandler(String urlPrefix) {
this.urlPrefix = urlPrefix;
}
//Failure logic:
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//We inherited that method:
saveException(request, exception);
//Prepare URL:
String username = request.getParameter(formUsernameKey);
String redirectUrl = urlPrefix + username;
//Redirect:
redirectStrategy.sendRedirect(request, response, redirectUrl);
}
//Getters and setters:
public String getUrlPrefix() {
return urlPrefix;
}
public void setUrlPrefix(String urlPrefix) {
this.urlPrefix = urlPrefix;
}
public String getFormUsernameKey() {
return formUsernameKey;
}
public void setFormUsernameKey(String formUsernameKey) {
this.formUsernameKey = formUsernameKey;
}
public RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
}
豆:
<bean class="some.package.UsernameInURLAuthenticationFailureHandler">
<!-- prefix: -->
<constructor-arg value="/login/failure/"/>
</bean>
您可以轻松实施 2) 策略。只需将用户名保存为onAuthenticationFailure
方法内的会话属性之一,而不是将用户名添加到 URL。
您可以轻松设置自己的处理程序:
<form-login>
属性
authentication-failure-handler-ref
可用作 authentication-failure-url 的替代方案,让您在身份验证失败后完全控制导航流程。该值应该是应用程序上下文中 AuthenticationFailureHandler bean 的名称。
更多文档:点击