gpt4 book ai didi

java - 如何基于@Profile 向 spring-security 添加过滤器?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:04:39 27 4
gpt4 key购买 nike

我试图定义两个不同的 bean(都扩展了 AbstractPreAuthenticatedProcessingFilter):一个用于在“开发”配置文件处于 Activity 状态时从请求(例如 USER_ID)中获取 header ,第二个用于从请求中获取 JWT当“开发”配置文件处于 Activity 状态时请求 header 。 (虽然从概念上讲,我真的只是试图根据 bean 本身的存在以编程方式注册过滤器)目前,我什至没有尝试使用配置文件,因为我在自动获取 header 方面遇到了问题在适当的过滤器链中注册。

该应用程序使用 Spring-Boot 2.0.0.RELEASE,配置为使用嵌入式 Tomcat,并且该服务被注释为 @RestController。下面是我的 SecurityConfig 类的简化版本:

@Configuration
@EnableWebSecurity(debug=true)
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


@Bean
public UserIdAuthenticationFilter UserIdAuthenticationFilter() throws Exception {
...
}

@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
...
}


@Override
protected void configure(HttpSecurity http) throws Exception {

http
.cors().and()
.csrf().disable()
.headers().frameOptions().sameOrigin()
.and()
//.addFilter(jwtAuthenticationFilter())
//.addFilter(UserIdAuthenticationFilter())
.exceptionHandling()
.and().authorizeRequests()
.antMatchers("/", "/index.html", "/css/**", "/images/**", "/js/**").permitAll()
.anyRequest()
.authenticated()
.antMatchers("/**").permitAll()
;


}

}

如您所见,我已经定义了我的过滤器 bean,它们在应用于正确的链时工作...我看到的问题是 spring 似乎在某处,但是当我调用服务端点时,它从不调用我添加的过滤器代码。

运行应用程序的日志输出似乎表明正在定位过滤器...

 2018-04-04 09:43:02.907  INFO 7717 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-04-04 09:43:02.907 INFO 7717 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-04-04 09:43:02.907 INFO 7717 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-04-04 09:43:02.908 INFO 7717 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-04-04 09:43:02.908 INFO 7717 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-04-04 09:43:02.908 INFO 7717 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpTraceFilter' to: [/*]
2018-04-04 09:43:02.908 INFO 7717 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'webMvcMetricsFilter' to: [/*]
2018-04-04 09:43:02.908 INFO 7717 --- [ LOOK HERE ] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'userIdAuthenticationFilter' to: [/*]
2018-04-04 09:43:02.908 INFO 7717 --- [ LOOK HERE ] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'jwtAuthenticationFilter' to: [/*]
2018-04-04 09:43:02.909 INFO 7717 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-04-04 09:43:02.922 DEBUG 7717 --- [ost-startStop-1] g.n.a.f.w.c.a.f.JwtAuthenticationFilter : Initializing filter 'jwtAuthenticationFilter'
2018-04-04 09:43:02.922 DEBUG 7717 --- [ost-startStop-1] g.n.a.f.w.c.a.f.JwtAuthenticationFilter : Filter 'jwtAuthenticationFilter' configured successfully
2018-04-04 09:43:02.922 DEBUG 7717 --- [ost-startStop-1] c.a.f.UserIdAuthenticationFilter : Initializing filter 'userIdAuthenticationFilter'
2018-04-04 09:43:02.922 DEBUG 7717 --- [ost-startStop-1] c.a.f.UserIdAuthenticationFilter : Filter 'userIdAuthenticationFilter' configured successfully

现在应用程序正在运行,当我尝试访问该服务时,我看到 spring dump 以下输出(启用调试):

 Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CorsFilter
LogoutFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]

根据该输出,它向我表明安全过滤器链没有应用我的过滤器。

也许更能说明问题的是,如果您注意到我的配置代码片段中有两行被注释掉了(这是我在尝试使用基于配置文件的检测之前手动添加过滤器的地方)。如果我取消注释添加 JWT 过滤器的行(也就是手动注册过滤器,而不是依赖检测),一切似乎都按预期工作。查看调试输出,我现在在手动添加过滤器后调用端点时看到以下内容(注意 JwtAuthenticationFilter 现在存在于安全过滤器链中):

 Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CorsFilter
LogoutFilter
JwtAuthenticationFilter <-----
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]

我真的有两个问题要问...我显然不理解 spring-boot/spring-security 设置的各种过滤器链,那么在应用程序启动期间注册的 bean 之间有什么区别在正常的过滤器链中,与在 spring-security 过滤器链中注册的 bean 相比?有人可以指出我做错了什么以及为什么吗?

注册这些“可选”bean 的正确方法是什么? (可选,因为可能不存在取决于 Activity 配置文件。)

谢谢!

最佳答案

来自article关于 Spring Security 架构:

Spring Security is installed as a single Filter in the chain, and its concerete type is FilterChainProxy, for reasons that will become apparent soon. In a Spring Boot app the security filter is a @Bean in the ApplicationContext, and it is installed by default so that it is applied to every request.

There can be multiple filter chains all managed by Spring Security in the same top level FilterChainProxy and all unknown to the container. The Spring Security filter contains a list of filter chains, and dispatches a request to the first chain that matches it.

另请注意:

The fact that all filters internal to Spring Security are unknown to the container is important, especially in a Spring Boot application, where all @Beans of type Filter are registered automatically with the container by default. So if you want to add a custom filter to the security chain, you need to either not make it a @Bean or wrap it in a FilterRegistrationBean that explicitly disables the container registration.

因此,当您将过滤器定义为 Spring bean 时,它会自动注册到 servlet 容器,但不会注册到 Spring Security 过滤器链。这就是为什么您需要使用 addFilter 方法将其显式添加到 Spring Security 链中。您还需要在 servlet 容器中禁用自动注册,否则过滤器将被调用两次。

另见:

至于配置文件,至少有两种方法可以满足您的需要:

  1. 扩展 AbstractHttpConfigurer 并将常见的安全配置移到那里。之后为每个配置文件创建一个单独的安全配置:

    @Configuration
    @EnableWebSecurity(debug = true)
    @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true, securedEnabled = true)
    public class SecurityConfiguration {

    /**
    * Development security configuration.
    */
    @Profile("dev")
    @Configuration
    public static class DevSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public FilterRegistrationBean userIdAuthenticationFilter() {
    // ...
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.apply(commonSecurityConfiguration())
    .and().addFilter(userIdAuthenticationFilter().getFilter());
    }
    }

    /**
    * Production security configuration.
    */
    @Profile("!dev")
    @Order(1)
    @Configuration
    public static class ProdSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public FilterRegistrationBean jwtAuthenticationFilter() {
    // ...
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.apply(commonSecurityConfiguration())
    .and().addFilter(jwtAuthenticationFilter().getFilter());
    }
    }


    /**
    * Common security configuration reused by all profiles.
    */
    public static class CommonSecurityConfiguration
    extends AbstractHttpConfigurer<CommonSecurityConfiguration, HttpSecurity> {

    @Override
    public void init(HttpSecurity http) throws Exception {
    // Your basic configuration here:
    // http.cors().and()
    // ...
    }

    public static CommonSecurityConfiguration commonSecurityConfiguration() {
    return new CommonSecurityConfiguration();
    }
    }
    }

    另请参阅 documentation 中的示例.

  2. 注入(inject)环境对象并检查当前配置文件:

    @Configuration
    @EnableWebSecurity(debug = true)
    @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true, securedEnabled = true)
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final Environment environment;

    public SecurityConfiguration(Environment environment) {
    this.environment = environment;
    }

    @Profile("dev")
    @Bean
    public FilterRegistrationBean userIdAuthenticationFilter() {
    // ...
    }

    @Profile("!dev")
    @Bean
    public FilterRegistrationBean jwtAuthenticationFilter() {
    // ...
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    // Your basic configuration here:
    // http.cors().and()
    // ...

    if (environment.acceptsProfiles("dev")) {
    http.addFilter(userIdAuthenticationFilter().getFilter());
    } else {
    http.addFilter(jwtAuthenticationFilter().getFilter());
    }
    }
    }

    或者,您可以为此使用应用程序属性而不是配置文件。

关于java - 如何基于@Profile 向 spring-security 添加过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49654751/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com