Search code examples
javaspringspring-bootjwtmicroservices

How to consume a JWT secured microservice from another microservice Java


My application has several microservices including: Auth, Game and Group. When I press a button on front end (Play) I'm calling Group rest api method, let's say foo(). In order to implement foo() inside Group I need to GET call Game rest api, but it's secured.

When I login in on React app I get the JWT token from /login (Auth) and store it in localstorage. Then I successfully use it to call foo() from Group but in foo() implementation I also need to use the jwt token in order to be able to get information from Game.

@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() is used in foo() method from Group. It's supposed to retrieve the minimum number of players of a game by id, but the game microservice is jwt secured and i get an unauthorized error.

So my question is how can i make Group microservice be able to call Game microservice.

Thanks.

Edit: RestTemplate Interceptor This is how I solved it.


Solution

  • Even if I have some security issues, I will answer this question :

    What you could do is :

    1. add an interceptor for incoming calls on your Group service that will store the JWT in the request context.
    2. add an interceptor for outgoing calls to your Game service that will get the JWT in the request context and add it to the request headers.

    What is important here is the request context.