[英]How to consume a JWT secured microservice from another microservice Java
我的應用程序有幾個微服務,包括:Auth、Game 和 Group。 當我按下前端(播放)上的按鈕時,我正在調用 Group rest api 方法,比如說 foo()。 為了在 Group 內實現 foo(),我需要 GET 調用 Game rest api,但它是安全的。
當我登錄 React 應用程序時,我從 /login (Auth) 獲取 JWT 令牌並將其存儲在 localstorage 中。 然后我成功地使用它從 Group 調用 foo() 但在 foo() 實現中,我還需要使用 jwt 令牌才能從游戲中獲取信息。
@Configuration
//+component scans...
public class GroupConfiguration {
@Bean
@LoadBalanced
public WebClient.Builder buildWebClientBuilder() {
return WebClient.builder();
}
}
@RestController
@RequestMapping("/groups")
public class Controller {
private final Logger logger = LogManager.getLogger();
@Autowired
private WebClient.Builder webClientBuilder;
private int getMinimumNumberOfPlayers(int gameId) {
try {
return webClientBuilder.build()
.get()
.uri("http://game-service/games/minimumNumberOfPlayers/2")
.retrieve()
.bodyToMono(Integer.class)
.block();
} catch (NullPointerException|WebClientResponseException e) {
e.printStackTrace();
return 0;
}
}
...
// foo() frontend calls foo(). foo it's using getMinimumNumberOfPlayers
getMinimumNumberOfPlayers() 用於 Group 的 foo() 方法。 它應該通過 id 檢索游戲的最小玩家數量,但是游戲微服務是 jwt 安全的,我收到了未經授權的錯誤。
所以我的問題是如何讓 Group 微服務能夠調用 Game 微服務。
謝謝。
編輯: RestTemplate Interceptor這就是我解決它的方法。
即使我有一些安全問題,我也會回答這個問題:
你可以做的是:
request context
存儲 JWT。request context
獲取 JWT 並將其添加到請求標頭中。 這里重要的是request context
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.