首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用spring security从失败的登录中获取用户名?

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

Stack Overflow用户
提问于 2011-12-30 12:36:46
回答 7查看 24.4K关注 0票数 26

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

代码语言:javascript
复制
<form-login login-page="/index.html" default-target-url="/postSignin.html" always-use-default-target="true"
 authentication-failure-handler-ref="authenticationFailureHandler"/>

我们的authenticationFailureHandler定义为:

代码语言:javascript
复制
<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>

Java

代码语言:javascript
复制
    @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.htmlIndexController。在IndexController中,我想要获取用于失败的登录尝试的username。我该怎么做呢?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2011-12-31 00:46:39

好的,据我所知,答案是非常简单的,没有过多的讨论或记录。

这是我要做的(没有任何配置,只是创建了这个类)……

代码语言:javascript
复制
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安全专家,所以如果有人读了这篇文章,知道我们不应该这样做的原因,或者知道更好的方法,我很乐意听到。

票数 27
EN

Stack Overflow用户

发布于 2014-12-12 03:14:14

我是这样做的:

  1. 创建了一个扩展onAuthenticationFailure方法的类,该方法以HttpServletRequest形式接收一个"username",其中

是我在onAuthenticationFailure表单中输入的名称。

票数 19
EN

Stack Overflow用户

发布于 2011-12-30 22:19:32

相反,您可以提供自己版本的DefaultAuthenticationEventPublisher并覆盖publishAuthenticationFailure方法。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8676206

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档