I'm trying to dynamically obtain public key from keycloak's cert url in my resource server. The url is load balanced (lb://app-auth/...) but nimbus is unable to resolve the host.

I'm certain the url is correct because I've tested it with the exact url and returned the keys.

Error log:

java.lang.IllegalStateException: Could not obtain the keys
        at org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder$JwkSetUriReactiveJwtDecoderBuilder.lambda$null$2(NimbusReactiveJwtDecoder.java:382) ~[spring-security-oauth2-jose-5.4.5.jar!/:5.4.5]

org.springframework.web.reactive.function.client.WebClientRequestException: failed to resolve 'app-auth'; nested exception is java.net.UnknownHostException: failed to resolve 'app-auth'
        at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.lambda$wrapException$9(ExchangeFunctions.java:141) ~[spring-webflux-5.3.5.jar!/:5.3.5]
        Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
        |_ checkpoint ⇢ Request to GET lb://app-auth/auth/realms/myrealm/protocol/openid-connect/certs [DefaultWebClient]

java.net.UnknownHostException: failed to resolve 'app-auth'

Resource server config:

@EnableWebFluxSecurity
class SecurityConfig {

    private val jwkUrl = "lb://app-auth/auth/realms/app/protocol/openid-connect/certs"

    @Bean
    fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain? {
        http.csrf().disable()
            .cors().and()
            .authorizeExchange()
            .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .pathMatchers("/**").hasAuthority("SCOPE_trust")
            .anyExchange().authenticated()
            .and()
            .oauth2ResourceServer()
            .jwt()
            .jwtAuthenticationConverter(AuthenticationConverter())
        return http.build()
    }

    @Bean
    @Throws(Exception::class)
    fun reactiveJwtDecoder(): ReactiveJwtDecoder? {
        return NimbusReactiveJwtDecoder.withJwkSetUri(jwkUrl).build()
    }
}

Is it even possible to have load balanced url? If so, how can I achieve this?

1

There are 1 best solutions below

0
On

So, turns out, It's possible to call load balance url. It just needs a load balanced WebClient:

@Bean
fun webClient(loadBalancerFactory: ReactiveLoadBalancer.Factory<ServiceInstance>): WebClient {
    return WebClient.builder()
        .filter(
            ReactorLoadBalancerExchangeFilterFunction(
                loadBalancerFactory, LoadBalancerProperties(), emptyList()
            )
        )
        .build()
}

And pass the WebClient using builder:

@Autowired
private lateinit var webClient: WebClient

@Bean
@Throws(Exception::class)
fun reactiveJwtDecoder(): ReactiveJwtDecoder? {
    return NimbusReactiveJwtDecoder.withJwkSetUri(jwkUrl)
        .webClient(webClient)
        .build()
}