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

前端 未结 3 677
情话喂你
情话喂你 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;
      }
      

提交回复
热议问题