使用applicationlistener spring security 4 annotation限制登录尝试

时间:2016-07-15 05:55:58

标签: spring spring-security spring-security-ldap

我已经使用了应用程序监听器敌人限制登录尝试但无法获得注册此应用程序监听器的位置,因为我的项目是基于没有xml的完整注释

身份验证听众

@Component
public class AuthenticationListener implements ApplicationListener <AbstractAuthenticationEvent>
{

    @Override
    public void onApplicationEvent(AbstractAuthenticationEvent appEvent)
    {
        System.out.println("got in authentication here");        
        if (appEvent instanceof AuthenticationSuccessEvent)
      {
          AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;
          // add code here to handle successful login event
          System.out.println("THERE WAS A SUCCESSFUL LOGIN");
      }

      if (appEvent instanceof AuthenticationFailureBadCredentialsEvent)
      {
          AuthenticationFailureBadCredentialsEvent event = (AuthenticationFailureBadCredentialsEvent) appEvent;

          // add code here to handle unsuccessful login event
          // for example, counting the number of login failure attempts and storing it in db
          // this count can be used to lock or disable any user account as per business requirements
          System.out.println("THERE WAS A UNSUCCESSFUL LOGIN");
      }
    }
}

SpringSecurity

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurity extends WebSecurityConfigurerAdapter {

//  @Autowired
//  @Qualifier("authenticationProvider")
//  static AuthenticationProvider authenticationProvider;
//
//  @Autowired
//  public static void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//      auth.authenticationProvider(authenticationProvider);
//  }

@Override
protected void configure(HttpSecurity http) throws Exception {
try{
    System.out.println("----TOP--------Http Security");
    http
    //.httpBasic()
    //.and()
    //.sessionCreationPolicy(SessionCreationPolicy.NEVER)
    //.and()
    .authorizeRequests()
    //.antMatchers(HttpMethod.GET,"/employees").access("hasRole('ROLE_idAdmin') or hasRole('ROLE_dAdmin')")
    .antMatchers(HttpMethod.GET,"/employees/?*").access("hasRole('ROLE_technician') or hasRole('ROLE_DADMIN') or hasRole('ROLE_IDADMIN') or hasRole('ROLE_WADMIN')")
    //.antMatchers(HttpMethod.POST,"/employees").access("hasRole('ROLE_IDADMIN') or hasRole('ROLE_DADMIN')")
    .and()
    .formLogin()
    //.antMatchers(HttpMethod.PUT,"/employees").access("hasRole('ROLE_IDADMIN') or hasRole('ROLE_DRADMIN') or hasRole('ROLE_WADMIN')")
    //.antMatchers(HttpMethod.DELETE,"/employees").access("hasRole('ROLE_IDADMIN')")
    //.antMatchers("/main").access("hasRole('ROLE_SUPERADMIN')")
    //.antMatchers("/confidential/**").access("hasRole('ROLE_SUPERADMIN')")
//  .exceptionHandling().accessDeniedPage("/index.jsp")

//  .and()
//    .httpBasic();
    //.and()
    //.logout()
        //.permitAll();
    ;
        System.out.println("----Bottom--------Http Security");
    //.logout();

//getConnection();
    //http.addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class);
     http.csrf().disable();
}
catch(Exception e){
    System.out.println("http Security error");
    e.printStackTrace();
}
}

@Configuration
protected static class AuthenticationConfiguration extends
        GlobalAuthenticationConfigurerAdapter {

//  @Autowired
//  //@Qualifier("authenticationProvider")
//  static AuthenticationProvider authenticationProvider;

    @Override
    //@Autowired//custom addition
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        System.out.println("1111111111111111Authentication Manager Got here1111111");


        auth
        .ldapAuthentication()
        .userSearchFilter("uid={0}")
        .userSearchBase("ou=users")
        .groupSearchFilter("uniqueMember={0}")
        .groupSearchBase("ou=groups")
        .groupRoleAttribute("cn")
        .rolePrefix("ROLE_")
        .contextSource(getLdapContextSource());

        //auth.authenticationProvider(authenticationProvider);
        System.out.println("Authentication Manager Got here");
    }
    private LdapContextSource getLdapContextSource() throws Exception {
        LdapContextSource cs = new LdapContextSource();
        cs.setUrl("ldap://localhost:1389/");
        cs.setBase("o=id workshop");
        cs.setUserDn("uid=admin,ou=system");
        cs.setPassword("secret");
        cs.afterPropertiesSet();
        return cs;
    }
    }
}

AppInitializer

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationListener;
//import org.krams.tutorial.controller.Equivalentwebxml;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.authenticationattempt.AuthenticationListener;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { EquivalentServlet.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

EquivalentServlet

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.security.SpringSecurity;

@EnableWebMvc
@Configuration
@ComponentScan({ "com.controller" })
@Import(value = { SpringSecurity.class })
//@Import(value = { AuthenticationListener.class})
public class EquivalentServlet {
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        //viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }



}

0 个答案:

没有答案