我目前正在努力将代理与Spring-Webflux结合使用。在其他服务中,我始终遵循这种方法,该方法非常有效(从标准环境变量中检索代理配置):
@Bean
public RestTemplate restTemplate() {
final RestTemplate restTemplate = new RestTemplate();
final CloseableHttpClient client = HttpClientBuilder.create().useSystemProperties().build();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(client));
return restTemplate;
}
但是现在我尝试使用Spring Oauth-Resource-Server软件包设置OAuth-Ressource-Server。该软件包将Spring-Webflux用于HTTP(S)。现在,该服务尝试从给定的uri中获取jwk集(需要代理),并且由于连接被拒绝错误而失败。是否有人将Spring-Webflux / OAuth-Ressource和代理结合使用?
我自己发现,为NimbusReactiveJwtDecoder bean提供正确配置的Web客户端可以解决此问题。
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.tcp.ProxyProvider;
@Data
@Component
@Configuration
@ConfigurationProperties(value = "proxy")
public class ProxyConfig {
private String host;
private int port;
private String username;
private String password;
@Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
private String jwkSetUri;
@Bean
public WebClient webClient(ReactorClientHttpConnector reactorClientHttpConnector) {
return WebClient.builder().clientConnector(reactorClientHttpConnector).build();
}
@Bean
public HttpClient httpClient() {
return HttpClient.create()
.tcpConfiguration(tcpClient ->
tcpClient.proxy(
proxy -> proxy.type(ProxyProvider.Proxy.HTTP).host(host)
.port(port).username(username)
.password(s -> password)));
}
@Bean
ReactorClientHttpConnector reactorClientHttpConnector(HttpClient httpClient) {
return new ReactorClientHttpConnector(httpClient);
}
@Bean
public NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder(WebClient webClient) {
return NimbusReactiveJwtDecoder
.withJwkSetUri(jwkSetUri)
.webClient(webClient).build();
}
}