如何使用spring安全性从失败的登录中获取用户名?

2022-09-01 15:18:38

我们使用的是 spring security 3.0.5、Java 1.6 和 Tomcat 6.0.32。在我们的.xml配置文件中,我们得到了:

<form-login login-page="/index.html" default-target-url="/postSignin.html" always-use-default-target="true"
 authentication-failure-handler-ref="authenticationFailureHandler"/>

和我们的定义为:authenticationFailureHandler

<beans:bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
   <beans:property name="exceptionMappings">
      <beans:props>
    <beans:prop key="org.springframework.security.authentication.BadCredentialsException">/index.html?authenticationFailure=true</beans:prop>
    </beans:props>
   </beans:property>
</beans:bean>

爪哇岛

    @RequestMapping(params={"authenticationFailure=true"}, value ="/index.html")
    public String handleInvalidLogin(HttpServletRequest request) {
       //...  How can I get the username that was used???
       // I've tried:
       Object username = request.getAttribute("SPRING_SECURITY_LAST_USERNAME_KEY");
       Object username = request.getAttribute("SPRING_SECURITY_LAST_USERNAME");  // deprecated
    }

因此,我们将所有内容都指向 和 。在“我想获取用于失败的登录尝试”中。我该怎么做?BadCredentialsExceptionsindex.htmlIndexControllerIndexControllerusername


答案 1

好吧,所以答案被证明是非常简单的,但据我所知,没有经过大量讨论或记录。

这就是我所要做的(任何地方都没有配置,只是创建了这个类)...

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

@Component
public class MyApplicationListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
    private static final Logger LOG = Logger.getLogger(MyApplicationListener.class);

    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
        Object userName = event.getAuthentication().getPrincipal();
        Object credentials = event.getAuthentication().getCredentials();
        LOG.debug("Failed login using USERNAME [" + userName + "]");
        LOG.debug("Failed login using PASSWORD [" + credentials + "]");
    }
}

我远非春季安全专家,所以如果有人读到这篇文章并知道我们不应该这样做的原因,或者知道一个更好的方法,我很想听听它。


答案 2

我是这样做的:

  1. 创建了一个扩展的类SimpleUrlAuthenticationFailureHandler

  2. 重写该方法,该方法接收 作为参数。onAuthenticationFailureHttpServletRequest

  3. request.getParameter("username"),其中是我在 HTML 表单中的输入的名称。"username"


推荐