如何在运行时修改Spring Security过滤器链?

时间:2018-02-09 08:17:59

标签: java spring spring-security

我正在使用Spring安全性,我的配置看起来像这样。我正在使用Spring Security SAML库。

http
    .addFilterBefore(metadataGeneratorFilter(samlEntryPoint, extendedMetadata), ChannelProcessingFilter.class)
    .addFilterAfter(samlFilter(samlEntryPoint, contextProvider), BasicAuthenticationFilter.class)
    .authenticationProvider(samlAuthenticationProvider);

private FilterChainProxy samlFilter(SAMLEntryPoint samlEntryPoint, SAMLContextProvider contextProvider) {
        List<SecurityFilterChain> chains = new ArrayList<>();
        chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"),
            samlEntryPoint));
        chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/metadata/**"),
            new MetadataDisplayFilter()));
        try {
            chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"),
                samlWebSSOProcessingFilter(samlAuthenticationProvider, contextProvider, samlProcessor)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        SAMLDiscovery samlDiscovery = new SAMLDiscovery();
        samlDiscovery.setMetadata(cachingMetadataManager);
        samlDiscovery.setContextProvider(contextProvider);
        chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"),
            samlDiscovery));
        return new FilterChainProxy(chains);
    }

现在,由于我的应用程序支持动态配置,如果IDP SSO网址从/saml/SSO更改为其他内容,则后续过滤器将无法正常工作,因为网址是硬编码的,配置只有在服务器重启后才会生效。

chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"),
                    samlWebSSOProcessingFilter(samlAuthenticationProvider, contextProvider, samlProcessor)));

有没有办法在运行时更改过滤器?我可以在Official Spring docs中看到getRequestMatcher()方法,但无法设置它。我是以错误的方式解决问题了吗?

1 个答案:

答案 0 :(得分:2)

我认为您可以实现自定义的RequestMatcher来检查网址:

public class CustomizedAntRequestMatcher implements RequestMatcher {
    @Override
    public boolean matches(HttpServletRequest request) {
        String url = "/saml/SSO/**"; //change this line to get your dynamic configuration
        AntPathRequestMatcher antPathRequestMatcher = new AntPathRequestMatcher(url);
        return antPathRequestMatcher.matches(request);
    }
}

然后使用自定义请求匹配器替换AntPathRequestMatcher:

chains.add(new DefaultSecurityFilterChain(new CustomizedRequestMatcher(),
                    samlWebSSOProcessingFilter(samlAuthenticationProvider, contextProvider, samlProcessor)));

如果这种方式无法解决您的问题,请与我联系。