ch4mpy / spring-addons

Ease spring OAuth2 resource-servers configuration and testing
Apache License 2.0
521 stars 84 forks source link

(Not a bug, jus a question) How do I add a filter ? #162

Closed david-randoll closed 8 months ago

david-randoll commented 8 months ago

First of all, I want to thank you guys for this awesome library. I used it for the multi-tenancy feature.

I want to add a tenantFilter (OncePerRequestFilter) into my configuration like below. How do I do this using Spring Addons? Thank you in advance!

    @Bean
    SecurityFilterChain securityFilterChain(
            HttpSecurity http,
            AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver,
            TenantFilter tenantFilter
    ) throws Exception {
        return http
            .authorizeHttpRequests(request -> request
                .requestMatchers("/actuator/**").permitAll()
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.authenticationManagerResolver(authenticationManagerResolver))
            .addFilterBefore(tenantFilter, BearerTokenAuthenticationFilter.class)
            .build();
    }
david-randoll commented 8 months ago

I was able to do this.

    @Bean
    ResourceServerHttpSecurityPostProcessor httpSecurityPostProcessor() {
        // @formatter:off
        return http -> http
                .addFilterBefore(tenantFilter, BearerTokenAuthenticationFilter.class);
        // @formatter:on
    }
ch4mpy commented 8 months ago

@david-randoll yes, this is probably the best way to add a filter to you filter-chain.