Spring安全身份验证:获取没有SPRING_SECURITY_LAST_USERNAME的用户名

dro*_*dpl 10 security authentication spring jsp login

我是Spring框架的新手.我正在为我的webapp创建一个登录页面,我希望用户在应用程序上的任何操作之前登录.如果用户输入了良好的凭据,那么一切正常并且正常工作,但是如果输入了坏的,我想显示一条消息,并在输入元素上保留用户名.显示消息不是问题,但是我不能在不使用已弃用的变量SPRING_SECURITY_LAST_USERNAME的情况下将用户名保留在我的jps文件中.

希望有人可以帮助我,我正在使用Spring 3.

更新:要求说我不想在网址上显示用户名.

zag*_*gyi 22

不推荐使用的常量的文档准确说明了您应该做什么:

/**
 * @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";
Run Code Online (Sandbox Code Playgroud)

像这样的东西:

public class UserNameCachingAuthenticationFailureHandler
    extends SimpleUrlAuthenticationFailureHandler {

    public static final String LAST_USERNAME_KEY = "LAST_USERNAME";

    @Autowired
    private UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter;

    @Override
    public void onAuthenticationFailure(
            HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception)
            throws IOException, ServletException {

        super.onAuthenticationFailure(request, response, exception);

        String usernameParameter =
            usernamePasswordAuthenticationFilter.getUsernameParameter();
        String lastUserName = request.getParameter(usernameParameter);

        HttpSession session = request.getSession(false);
        if (session != null || isAllowSessionCreation()) {
            request.getSession().setAttribute(LAST_USERNAME_KEY, lastUserName);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的安全配置中:

<security:http ...>
    ...
    <security:form-login
        authentication-failure-handler-ref="userNameCachingAuthenticationFailureHandler"
    ...
    />
</security:http>

<bean 
    id="userNameCachingAuthenticationFailureHandler"
    class="so.UserNameCachingAuthenticationFailureHandler">
    <property name="defaultFailureUrl" value="/url/to/login?error=true"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

在你的login.jsp中:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="true" %>

...

<%--in the login form definition--%>
<input id="j_username" name="j_username" type="text" 
    value="<c:out value="${sessionScope.LAST_USERNAME}"/>"/>
Run Code Online (Sandbox Code Playgroud)

  • 如果您将其实现为自定义 bean,则也可以从“RedirectStrategy.sendRedirect()”方法成功调用“request.getParameter("j_username")”(实际上该 bean 是“AuthenticationFailureHandler”的成员变量/字段)类/bean)。 (2认同)
  • usernamePasswordAuthenticationFilter为null.Spring Security 4.我该如何解决这个问题? (2认同)