如何使用oauth2 grant_type = password监听登录失败/成功

时间:2016-07-12 12:46:46

标签: spring spring-security spring-cloud spring-oauth2

我的应用程序使用spring cloud oauth2 rest and angular。

我的目标是使用spring服务器来限制最大登录失败次数

angular2登录代码:

const body = "username=" + encodeURI(username) + "&password=" + encodeURI(password) +
      "&grant_type=password&client_id=" + encodeURI(this.clientId);

this.http.post("/oauth/token",body,{headers:authHeaders}).map{
...
}

spring auth-server web安全码:

    @Override
      protected void configure(HttpSecurity http) throws Exception {

        http.httpBasic().and().sessionManagement()
              .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
              .and().authorizeRequests()
            .anyRequest().authenticated();
      }

我尝试了这两个事件:

public class AuthenticationFailureListener
    implements ApplicationListener<AuthenticationFailureBadCredentialsEvent>{
@Override
  public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent e) {
  //...
}
}

和:

public class AuthenticationSuccessListener
    implements ApplicationListener<AuthenticationSuccessEvent> {
  @Override
  public void onApplicationEvent(AuthenticationSuccessEvent e) {
//...
}
}
  

但它不起作用

如何倾听“登录失败并取得成功”?

1 个答案:

答案 0 :(得分:1)

Spring Security 默认 发布 AuthenticationFailureBadCredentialsEvent (登录失败)事件默认

您需要使用ApplicationEventPublisher 覆盖 DefaultAuthenticationEventPublisher。

必须在您的身份验证配置类中完成此操作,如下所示。

@Configuration
protected static class MyAuthenticationConfiguration extends
        GlobalAuthenticationConfigurerAdapter {

    @Value("${ldap.url}")
    String url;

    @Value("${ldap.base}")
    String base;

    @Value("${ldap.managerDn}")
    String managerDn;

    @Value("${ldap.password}")
    String password;

    @Autowired
    ApplicationEventPublisher applicationEventPublisher;


    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.ldapAuthentication().userSearchFilter("sAMAccountName={0}")
                .userSearchBase(base).contextSource().url(url)
                .managerDn(managerDn).managerPassword(password);
        //This publisher will trigger AuthenticationFailureBadCredentialsEvent (AbstractAuthenticationFailureEvent)
        auth.authenticationEventPublisher(new DefaultAuthenticationEventPublisher(applicationEventPublisher));

    }

要支持基于表单的身份验证,请在configure()方法中添加以下内容。

.and().formLogin();

整个配置方法应类似于以下内容。

@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests().antMatchers("/css/**").permitAll()
        .anyRequest().fullyAuthenticated().and().formLogin();
super.configure(http);

}
相关问题