0

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

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

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 网络安全代码:

    @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) {
//...
}
}

但它不起作用

如何收听“登录失败和成功”?

4

1 回答 1

1

Spring Security默认不会发布AuthenticationFailureBadCredentialsEvent (login failed) 事件。

您需要使用 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);

}
于 2016-07-12T16:07:37.437 回答