如何使用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"/>
和我们的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
}
因此,我们将所有内容都定向BadCredentialsExceptions
到index.html
和IndexController
。在中,IndexController
我想获取username
用于失败登录尝试的。我怎样才能做到这一点?
回答:
好的,据我所知,答案竟然是非常简单的事情,没有经过大量讨论或记录。
这就是我要做的(在创建此类的任何地方都无需配置)…
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 + "]");
}
}
我与Spring Security专家相距甚远,因此,如果有人读过此书,并且知道某个原因,我们就不应该这样做或知道我想听听它的更好方法。
以上是 如何使用Spring Security从登录失败中获取用户名? 的全部内容, 来源链接: utcz.com/qa/434588.html