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

kas*_*ega 22 java spring tomcat spring-security

我们使用的是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"/>
Run Code Online (Sandbox Code Playgroud)

我们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>
Run Code Online (Sandbox Code Playgroud)

Java的

    @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
    }
Run Code Online (Sandbox Code Playgroud)

因此,我们将所有人都BadCredentialsExceptions指向index.htmlIndexController.在IndexController我想要获得username用于失败登录尝试的那个.我怎样才能做到这一点?

kas*_*ega 23

好的,所以答案结果是非常简单的,但据我所知,没有经过深入讨论或记录.

这就是我必须做的所有事情(没有任何配置只是创建这个类)...

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 + "]");
    }
}
Run Code Online (Sandbox Code Playgroud)

我离春天的安全专家很远,所以如果有人读到这个并知道我们不应该这样做的理由,或者知道一个更好的方式我会喜欢听到它.


Raf*_*yng 17

我是这样做的:

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

  2. 覆盖onAuthenticationFailure方法,该方法接收HttpServletRequest作为参数.

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


Sai*_*ish 5

您可以改为提供自己的DefaultAuthenticationEventPublisher版本并覆盖publishAuthenticationFailure方法.