How to represent the Spring Security “custom-filter” using Java configuration?

前端 未结 3 658
情话喂你
情话喂你 2020-12-23 11:45

What is the equivalent Java configuration for the Spring Security tag?



        
相关标签:
3条回答
  • 2020-12-23 12:23

    A few issues you may need to keep in mind:

    1. Your filter needs to be added before the standard UsernamePasswordAuthenticationFilter

      
      http.addFilterBefore(customUsernamePasswordAuthenticationFilter(),
              UsernamePasswordAuthenticationFilter.class)
      
    2. If you extend UsernamePasswordAuthenticationFilter your filter will return immediately without doing anything unless you set a RequestMatcher

      
      myAuthFilter.setRequiresAuthenticationRequestMatcher(
          new AntPathRequestMatcher("/login","POST"));
      
    3. All the configuration you do in http.formLogin().x().y().z() is applied to the standard UsernamePasswordAuthenticationFilter not the custom filter you build. You will need to configure it manually yourself. My auth filter initialization looks like this:

      
      @Bean
      public MyAuthenticationFilter authenticationFilter() {
          MyAuthenticationFilter authFilter = new MyAuthenticationFilter();
          authFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login","POST"));
          authFilter.setAuthenticationManager(authenticationManager);
          authFilter.setAuthenticationSuccessHandler(new MySuccessHandler("/app"));
          authFilter.setAuthenticationFailureHandler(new MyFailureHandler("/login?error=1"));
          authFilter.setUsernameParameter("username");
          authFilter.setPasswordParameter("password");
          return authFilter;
      }
      
    0 讨论(0)
  • 2020-12-23 12:23

    Try to add @Component to your MyUsernamePasswordAuthenticationFilter class.

    This annotation makes the class considered as candidates for auto-detection, see: @Component


    For this:

    <custom-filter position="FORM_LOGIN_FILTER" ref="myFilter"/>
    

    You can add this:

    .addFilter[Before|After](authenticationTokenProcessingFilter, UsernamePasswordAuthenticationFilter.class)
    

    See: Standard Filter Aliases and Ordering

    0 讨论(0)
  • 2020-12-23 12:42

    I dont find any issue in this code. I think, your configuration is fine. Problem is somewhere else.I have similar code,

    package com.programsji.config;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.authentication.AuthenticationProvider;
    import org.springframework.security.authentication.ProviderManager;
    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.builders.WebSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    import com.programsji.security.CustomAuthenticationProvider;
    import com.programsji.security.CustomSuccessHandler;
    import com.programsji.security.CustomUsernamePasswordAuthenticationFilter;
    
    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/js/**", "/css/**", "/theme/**").and()
                    .debug(true);
        }
    
        @Bean
        public CustomUsernamePasswordAuthenticationFilter customUsernamePasswordAuthenticationFilter()
                throws Exception {
            CustomUsernamePasswordAuthenticationFilter customUsernamePasswordAuthenticationFilter = new CustomUsernamePasswordAuthenticationFilter();
            customUsernamePasswordAuthenticationFilter
                    .setAuthenticationManager(authenticationManagerBean());
            customUsernamePasswordAuthenticationFilter
                    .setAuthenticationSuccessHandler(customSuccessHandler());
            return customUsernamePasswordAuthenticationFilter;
        }
    
        @Bean
        public CustomSuccessHandler customSuccessHandler() {
            CustomSuccessHandler customSuccessHandler = new CustomSuccessHandler();
            return customSuccessHandler;
        }
    
        @Bean
        public CustomAuthenticationProvider customAuthenticationProvider() {
            CustomAuthenticationProvider customAuthenticationProvider = new CustomAuthenticationProvider();
            return customAuthenticationProvider;
        }
    
        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            List<AuthenticationProvider> authenticationProviderList = new ArrayList<AuthenticationProvider>();
            authenticationProviderList.add(customAuthenticationProvider());
            AuthenticationManager authenticationManager = new ProviderManager(
                    authenticationProviderList);
            return authenticationManager;
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().antMatchers("/reportspage").hasRole("REPORT")
                    .antMatchers("/rawdatapage").hasRole("RAWDATA").anyRequest()
                    .hasRole("USER").and().formLogin().loginPage("/login")
                    .failureUrl("/login?error")
                    .loginProcessingUrl("/j_spring_security_check")
                    .passwordParameter("j_password")
                    .usernameParameter("j_username").defaultSuccessUrl("/")
                    .permitAll().and().httpBasic().and().logout()
                    .logoutSuccessUrl("/login?logout").and().csrf().disable()
                    .addFilter(customUsernamePasswordAuthenticationFilter());
        }
    
    }
    

    It is working fine on my application. you can download this entire project from url: https://github.com/programsji/rohit/tree/master/UsernamePasswordAuthenticationFilter

    0 讨论(0)
提交回复
热议问题