我想創建一些用于 的身份驗證服務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
}
}
過期時它會正確獲取令牌。有沒有辦法只使用一次,而不將其注入其他服務?我正在考慮定義Beanwhich 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 請求并添加令牌?
uj5u.com熱心網友回復:
您可以宣告一個自定義過濾器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();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/450500.html
標籤:爪哇 春天 jwt spring-webflux 弹簧网络客户端
