How can I get the username from a failed login using spring security?

后端 未结 7 2269
情书的邮戳
情书的邮戳 2020-12-23 18:31

We\'re using spring security 3.0.5, Java 1.6 and Tomcat 6.0.32. In our .xml config file we\'ve got:



        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 18:57

    This is a pretty old thread, but if you are using a relatively current "spring-boot-starter-security" package, here's how I did it:

    I set my AuthenticationFailureHandler like so:

    SimpleUrlAuthenticationFailureHandler handler = new SimpleUrlAuthenticationFailureHandler("/my-error-url");
    handler.setUseForward(true);
    

    This will set the last exception into the request:

    //from SimpleUrlAuthenticationFailureHandler source
    request.setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception);
    

    Then from my controller I can get the bad username:

    RequestMapping("/impersonate-error")
    public String impersonateErrorPage(Map model, HttpServletRequest request) {
    
        AuthenticationException ex = (AuthenticationException)request.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        if(ex != null) {
            logger.debug("Impersonate message: " + ex.getMessage());
            model.put("badName", ex.getMessage());
        }
        return "impersonate-error";
    }
    

提交回复
热议问题