0

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 ?

Gog1nA
  • 376
  • 1
  • 8
  • 30

1 Answers1

0

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.

Gary Archer
  • 22,534
  • 2
  • 12
  • 24
  • So the only way is to extract Token from header in service B and put it in header while sending request to service C. I thought maybe there was better(more simply) solution. Do you have any topic where is described how can I extract token from request ? I am struggling to do it – Gog1nA Jul 02 '21 at 08:39
  • Inject the HttpServletRequest object if required - see [this answer](https://stackoverflow.com/questions/3320674/spring-how-do-i-inject-an-httpservletrequest-into-a-request-scoped-bean). You can then read the JWT with a [couple of lines of code](https://github.com/gary-archer/oauth.apisample.javaspringboot/blob/master/src/main/java/com/mycompany/sample/plumbing/oauth/BearerToken.java) – Gary Archer Jul 02 '21 at 17:51