我想创建一些用于 的身份验证服务WebClient
,因此它会在需要时自动刷新令牌:
@Service
public class AuthService {
private String token;
private final WebClient webClient;
private final Map<String, String> bodyValues;
@Autowired
public AuthService(WebClient webClient) {
this.webClient = webClient;
this.bodyValues = new HashMap<>();
this.bodyValues.put("user", "myUser");
this.bodyValues.put("password", "somePassword");
}
public String getToken() {
if (this.token == null || this.isExpired(this.token) {
this.refreshToken();
}
return this.token;
}
private void refreshToken() {
this.token = webClient.post()
.uri("authEndpointPath")
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(bodyValues))
.retrieve()
.bodyToMono(String.class)
.block();
}
private boolean isExpired() {
//implementation
}
}
过期时它会正确获取令牌。有没有办法只使用一次,而不将其注入其他服务?我正在考虑定义Bean
which usesauthService.getToken()
方法:
@Configuration
public class CustomWebClientConfig {
private final AuthService authService;
@Autowired
public CustomWebClientConfig(AuthService authService) {
this.authService = authService;
}
@Bean("myCustomWebClient")
WebClient webClient() {
return WebClient.builder()
.defaultHeader("Access-Token", authService.getToken())
.build()
}
}
但显然它只会在应用程序启动时获得一次令牌。有没有办法以某种方式注入它或拦截所有 webclient 请求并添加令牌?
您可以声明一个自定义过滤器WebClient
,该过滤器应用于每个请求。
@Configuration
public class CustomWebClientConfig {
private final AuthService authService;
@Autowired
public CustomWebClientConfig(AuthService authService) {
this.authService = authService;
}
@Bean("myCustomWebClient")
WebClient webClient() {
return WebClient.builder()
.filter(ExchangeFilterFunction.ofRequestProcessor(
(ClientRequest request) -> Mono.just(
ClientRequest.from(request)
.header("Access-Token", authService.getToken())
.build()
)
))
.build();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句