Learn how to pass OAuth2 token among microservices through Feign.

Assume we have two microservices, One is products and another is cart and for instance they want to communicate among themselves, so we have two widely used options.

  1. REST Template (Old way).
  2. Feign (New approach, also reduces lots of boilerplate code)

If we go with Feign client approach, code snippet looks like below (code of feign usually resides at calling service, in our case cart is calling products, so feign code will be at cart microservice)

Before OAuth2 implementation, feign code looks like below.

@FeignClient(name = "somename", url = "#{'${products.url}'}")
public interface ProductsServiceProxy {

@GetMapping("/allthewaytoproducts/my_products") 
public List<Products> getAllSelectedProducts();

}

Post OAuth2 is implemented, with both microservices registered with @EnableResourceServer, then simple feign call will end up with unauthorised access. And to make it work do below changes.

In cart microservice, once it has been called through zuul or SingleSignOn (sso) or through other UI means, access token would have been passed to cart service, so we should fetch access token first.

CartController.java

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String token = ((OAuth2AuthenticationDetails)auth.getDetails()).getTokenValue();

once token is retrieved, then pass it in feing using its header property.

Updated Feing code.

@FeignClient(name = "somename", url = "#{'${products.url}'}")
public interface ProductsServiceProxy {

@GetMapping("/allthewaytoproducts/my_products") 
public List<Products> getAllSelectedProducts(@RequestHeader(HttpHeaders.AUTHORIZATION) String token);

}

Wherever we are calling feing, pass token correspondingly like below.

@Autowired 
private ProductsServiceProxy proxy;
...
List<Products>= proxy.getAllSelectedProducts ("bearer "+token);

Above changes should be good to go, happy coding !!

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

14 − 12 =