Best way to PASS JWT tokens from one SPRING API to another

Viewed 1327

I like to get suggestions of SO users to find the best way to solve this problem.

I use an Identity manager (that supports openid-connect), a frontend client (alias FE), a BFF (alias BFF) and two backend APIs written in spring and spring boot re. My requirement is this;

  1. FE redirects to IDM - gets a JWT token after successful authentication. The JWT has correct claims as well, and the discovery URL has the public key to verify the JWT token as well. FE calls an API via its BFF
  2. BFF calls API-1 which in turn calls API-2.
  3. API-2 should validate the logged-in user to ensure that the "Manager" grant is associated to the JWT token

enter image description here The API-1 and API-2 above are two spring APIs and I am assuming for this question that BFF passes the jwt token to the API-1 and API-1 follows the recommended process to validate the token as well.

My question is what is the recommended way for the API-1 to get the token in the request headers and pass it to the API-2 using spring features.

(Currently, I use thread-locals to facilitate this i.e in the request filter I add the received header to a thread-local, then it carries out its logics and at the point of invoking API-2 I fetch the header on the thread-local space and pass it to API-2. I highly doubt that this is the recommended way of doing it...)

1 Answers

My question is what is the recommended way for the API-1 to get the token in the request headers and pass it to the API-2

You can specify the request header as the service method parameter

example

@GetMapping("/greeting")
public ResponseEntity<String> greeting(
  @RequestHeader("Authorization") String authnHeader) {

and you can use a RequestTemplate to pass the Authorization header value to the backend calls.

POST example2

MultiValueMap<String, String> headers = new 
LinkedMultiValueMap<String, String>();
headers.add("Authorization", authnHeader);
headers.add("Content-Type", "application/json");

RestTemplate restTemplate = new RestTemplate();

HttpEntity<ObjectToPass> request = new 
HttpEntity<ObjectToPass>(objectToPassInstance, headers);

restTemplate.postForObject(urlPost, request, Boolean.class);
Related