Spring Security addFilterAfter未注册过滤器

时间:2017-02-13 09:09:48

标签: java spring spring-mvc spring-boot spring-security

我正在开发一个Spring启动应用程序,我使用spring security来保护我的应用程序。我已经创建了一个自定义过滤器,我想在UsernamePasswordAuthenticationFilter之后添加它。我使用HttpSecurity.addFilterAfter方法来执行此操作。

但是,我的过滤器永远不会被调用。请你帮我解决这个问题。代码:

MultiSessionCustomLMSFilter.java

public class MultiSessionCustomLMSFilter extends GenericFilterBean {

private final static Logger log = LoggerFactory.getLogger(MultiSessionCustomLMSFilter.class);

@Autowired private UserLoginLogRepository userLoginLogRepository;
private ObjectMapper mapper;

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)   throws IOException, ServletException {
    log.debug("Inside doFilter of MultipleSessionFilter");
    //CUSTOM APP SPECIFIC LOGIC GOES IN HERE
    }
}

WebSecurityConfig.java

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    public static final String JWT_TOKEN_HEADER_PARAM = "X-Authorization";
    public static final String FORM_BASED_LOGIN_ENTRY_POINT = "/api/auth/login";
    public static final String CSRF_ENTRY_POINT = "/api/auth/login/csrf";
    public static final String TOKEN_BASED_AUTH_ENTRY_POINT = "/api/**";
    public static final String TOKEN_REFRESH_ENTRY_POINT = "/api/auth/token";

    @Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
    @Autowired private AuthenticationSuccessHandler successHandler;
    @Autowired private AuthenticationFailureHandler failureHandler;
    @Autowired private LoginAuthenticationProvider loginAuthenticationProvider;
    @Autowired private JwtAuthenticationProvider jwtAuthenticationProvider;

    @Autowired private TokenExtractor tokenExtractor;

    @Autowired private AuthenticationManager authenticationManager;

    @Autowired private ObjectMapper objectMapper;

    @Autowired private JwtTokenFactory jwtTokenFactory;

    protected LoginProcessingFilter buildAjaxLoginProcessingFilter() throws Exception {
        LoginProcessingFilter filter = new LoginProcessingFilter(FORM_BASED_LOGIN_ENTRY_POINT, successHandler, failureHandler, objectMapper);
        filter.setAuthenticationManager(this.authenticationManager);
        return filter;
    }

    protected JwtTokenAuthenticationProcessingFilter buildJwtTokenAuthenticationProcessingFilter() throws Exception {
        List<String> pathsToSkip = Arrays.asList(TOKEN_REFRESH_ENTRY_POINT,FORM_BASED_LOGIN_ENTRY_POINT, CSRF_ENTRY_POINT);
        SkipPathRequestMatcher matcher = new SkipPathRequestMatcher(pathsToSkip, TOKEN_BASED_AUTH_ENTRY_POINT);
        JwtTokenAuthenticationProcessingFilter filter = new JwtTokenAuthenticationProcessingFilter(failureHandler, tokenExtractor, matcher,objectMapper,jwtTokenFactory);
        filter.setAuthenticationManager(this.authenticationManager);
        return filter;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(loginAuthenticationProvider);
        auth.authenticationProvider(jwtAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
        .exceptionHandling()
        .authenticationEntryPoint(this.authenticationEntryPoint)

        .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

        .and()
            .authorizeRequests()
                .antMatchers(TOKEN_REFRESH_ENTRY_POINT).permitAll() // Token refresh end-point
                .antMatchers(CSRF_ENTRY_POINT).permitAll()
//              .antMatchers(MIQA_FORUM_ENTRY_POINT).permitAll()
        .and()
            .authorizeRequests()
                .antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated() // Protected API End-points
        .and().cors().and()
            .addFilterBefore(buildAjaxLoginProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
            .addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
            .addFilterAfter(new MultiSessionCustomLMSFilter(),UsernamePasswordAuthenticationFilter.class);

    }
调用过滤器时的

应用程序日志在引导期间:

    Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1,
 [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@a457c2b,
 org.springframework.security.web.context.SecurityContextPersistenceFilter@464aeb09,
 org.springframework.security.web.header.HeaderWriterFilter@32da97fd,
 org.springframework.web.filter.CorsFilter@16a6dc21,
 org.springframework.security.web.authentication.logout.LogoutFilter@c0c8f96,
 com.egmat.lms.security.auth.login.LoginProcessingFilter@5773d271,
 com.egmat.lms.security.auth.jwt.JwtTokenAuthenticationProcessingFilter@59f45950,
 com.egmat.lms.security.MultiSessionCustomLMSFilter@7871d261,
 org.springframework.security.web.savedrequest.RequestCacheAwareFilter@59d6642a,
 org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@288728e,
 org.springframework.security.web.authentication.AnonymousAuthenticationFilter@58164e9a,
 org.springframework.security.web.session.SessionManagementFilter@4aa22cc2,
 org.springframework.security.web.access.ExceptionTranslationFilter@e01a26b,
 org.springframework.security.web.access.intercept.FilterSecurityInterceptor@5c70d7f0]

1 个答案:

答案 0 :(得分:0)

JwtTokenAuthenticationProcessingFilterchain.doFilter(request, response); 是否会继续过滤链?

过滤器需要通过执行以下操作来继续过滤器链:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /

# Check if this is the noredirect query string
RewriteCond %{QUERY_STRING} (^|&)m=0(&|$)
# Set a cookie, and skip the next rule
RewriteRule ^ - [CO=mredir:0:mysite.com]

RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP:Profile}       !^$ [OR]
RewriteCond %{HTTP_USER_AGENT} "acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT}  "maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "wapp|wapr|webc|winw|winw|xda|xda-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "up.browser|up.link|windowssce|iemobile|mini|mmp" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "symbian|midp|wap|phone|pocket|mobile|pda|psp" [NC]
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC]

# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST}          !^m\.
# Can not read and write cookie in same request, must duplicate condition
RewriteCond %{QUERY_STRING} !(^|&)m=0(&|$) 

# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP_COOKIE}        !^.*mredir=0.*$ [NC]

# Now redirect to the mobile site
RewriteRule ^ http://m.mysite.com%{REQUEST_URI} [R,L]
</IfModule>
相关问题