Spring security authentication: get username without SPRING_SECURITY_LAST_USERNAME

后端 未结 2 1363
陌清茗
陌清茗 2021-02-08 04:37

I\'m new at spring framework. I\'m creating a login page for my webapp and I want the user to login before any action on the app. If the user enters good credentials everything

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-08 04:46

    The documentation of the deprecated constant tells exactly what you should do:

    /**
     * @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";
    

    Something like this:

    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);
            }
        }
    }
    

    In your security config:

    
        ...
        
    
    
    
        
    
    

    In your login.jsp:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ page session="true" %>
    
    ...
    
    <%--in the login form definition--%>
    "/>
    

提交回复
热议问题