Spring boot security, API-key protection OR oauth2 resourceServer for same resources

Viewed 214

I have a spring boot 2.4 application where I want to protect it with either an API-key or a resource server. I was thinking that I could use filters here to first check if the api key is given and if so, grant access to the resource, otherwhise a "second chance" should be given to authenticate with an opaque oauth2-token (api key for machine to machine, token for frontend -> backend)

Where I get stuck is that my security config looks like this today (with a resource server activated)

    @Bean
    fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain? =
        http.authorizeExchange()
            .anyExchange().authenticated()
            .and()
            .oauth2ResourceServer {
                it.authenticationManagerResolver(myMultiTenantResolver)
            }
            .build()

how would I go about to add an API-protection in here which should grant access (if it succeeds) without also invoking the resourceServer-snippet here (if it doesn't succeed, the resourceServer-snippet should be invoked)?

1 Answers

One possible solution can be as following:-

  1. Create both your filters i.e the api-key filter and the auth-token filter.
  2. In your configure(HttpSecurity http) method of ApplicationSecurityConfiguration add the api-key filter before the auth-token filter.
  3. If you pass the api-key, put you authentication details in securityContextHolder. In the next filter(auth-token filter) Override the doFilter, where you need to check that if the previous filter has been authenticated, you do not run the current filter(auth-token filter) by calling chain.doFilter(request, response).

Please let me know if you need the complete implementation.

Related