Search code examples
spring-bootspring-mvcoauth-2.0bearer-token

How to send authenticated request to another service in spring boot


I have 3 services 1 authentication service(for example service A) and other 2 services(for example service B and service C) which are using same authentication A service.

I have method in service B like

@PostMapping("/update-account")
    public ResponseEntity<Object> updateAccount(HttpServletRequest request,
                                                OAuth2Authentication principal,
                                                @RequestBody UpdateAccountDto updateAccountDto){


}

In this method I am calling other method where I have some logic and in the end I want to call endpoint of service C using restTemaplte like this

String serviceBEndpoint= "localhost:8090/testapi/updateAccount";
        URI serviceUri = UriComponentsBuilder.fromUriString(changeEmailUri)
                .build()
                .toUri();

        HttpHeaders headers = new HttpHeaders();
        headers.set("someheader", someheader);

        HttpEntity<UpdateUserDto> request = new HttpEntity<>(updadteUserDto, headers);
        restTemplate.postForEntity(serviceUri, request, AuthenticationSuccessDto.class);

User called endpoint of Service B with correct token(request is authenticated) and it is also legal to call service C from service B because request is authenticated, so how can I do it with correct way ?


Solution

  • The most common approach for microservices all owned by the same company works like this:

    • Client authenticates the user and gets an access token with rights to call both services B and C

    • The access token might therefore have scopes B and C - or something similar - related to the business of those services

    • Client calls service B and includes the access token in the HTTP Authorization header

    • This means service B can forward the token to service C, again in the HTTP Authorization header, and service C will accept it because it contains scope C. Looks like your Rest Template code above is nicely set up to enable this.

    • Both services B and C need to validate the access token in the standard way - see these guides for exanples.

    More on this pattern in this Scope Best Practices article.